【问题标题】:What is the easiest way to seeing if there are any matches across a few DateTime arrays?查看几个 DateTime 数组中是否有任何匹配项的最简单方法是什么?
【发布时间】:2013-02-16 17:32:50
【问题描述】:
如果我有 3 个来自不同来源的 DateTime 列表
List<Datetime> list1 = GetListOfDates();
List<Datetime> list2 = GetAnotherListOfDates();
List<Datetime> list3 = GetYetAnotherListOfDates();
返回所有 3 个列表中存在的 DateTime 列表的最快方法是什么。有一些 LINQ 语句吗?
【问题讨论】:
标签:
c#
linq
datetime
collections
【解决方案1】:
List<DateTime> common = list1.Intersect(list2).Intersect(list3).ToList();
【解决方案2】:
HashSet<DateTime> common = new HashSet<DateTime>( list1 );
common.IntersectWith( list2 );
common.IntersectWith( list3 );
HashSet 类对于此类任务比使用 Enumerable.Intersect 更有效。
更新:确保你所有的值都是相同的DateTimeKind。
【解决方案3】:
var resultSet = list1.Intersect<DateTime>(list2).Intersect<DateTime>(list3);
【解决方案4】:
您可以将列表相交:
var resultSet = list1.Intersect<DateTime>(list2);
var finalResults = resultSet.Intersect<DateTime>(list3);
foreach (var result in finalResults) {
Console.WriteLine(result.ToString());
}