異なるソースからの3つのDateTimeリストがある場合
List<Datetime> list1 = GetListOfDates();
List<Datetime> list2 = GetAnotherListOfDates();
List<Datetime> list3 = GetYetAnotherListOfDates();
3つのリストすべてに存在するDateTimeのリストを返す最も簡単な方法は何でしょうか。LINQステートメントはありますか?
異なるソースからの3つのDateTimeリストがある場合
List<Datetime> list1 = GetListOfDates();
List<Datetime> list2 = GetAnotherListOfDates();
List<Datetime> list3 = GetYetAnotherListOfDates();
3つのリストすべてに存在するDateTimeのリストを返す最も簡単な方法は何でしょうか。LINQステートメントはありますか?
List<DateTime> common = list1.Intersect(list2).Intersect(list3).ToList();
HashSet<DateTime> common = new HashSet<DateTime>( list1 );
common.IntersectWith( list2 );
common.IntersectWith( list3 );
このHashSet
ようなタスクには、クラスを使用するよりも効率的ですEnumerable.Intersect
。
更新:すべての値が同じであることを確認してくださいDateTimeKind
。
var resultSet = list1.Intersect<DateTime>(list2).Intersect<DateTime>(list3);
リストを交差させることができます:
var resultSet = list1.Intersect<DateTime>(list2);
var finalResults = resultSet.Intersect<DateTime>(list3);
foreach (var result in finalResults) {
Console.WriteLine(result.ToString());
}