What is the easiest way to see if there are matches in multiple DateTime arrays?

If I have 3 DateTime lists that come from different sources

 List<Datetime> list1 = GetListOfDates();
 List<Datetime> list2 = GetAnotherListOfDates();
 List<Datetime> list3 = GetYetAnotherListOfDates();

What would be the fastest way to return a DateTime list that exists in all three lists. Is there a LINQ instruction?

+5
source share
4 answers
List<DateTime> common = list1.Intersect(list2).Intersect(list3).ToList();
+5
source
HashSet<DateTime> common = new HashSet<DateTime>( list1 );
common.IntersectWith( list2 );
common.IntersectWith( list3 );

A class is HashSetmore efficient for such tasks than use Enumerable.Intersect.

Update: make sure all your values ​​match DateTimeKind.

+2
source
var resultSet = list1.Intersect<DateTime>(list2).Intersect<DateTime>(list3);
+1
source

You can cross the lists:

var resultSet = list1.Intersect<DateTime>(list2);
var finalResults = resultSet.Intersect<DateTime>(list3);

foreach (var result in finalResults) {
   Console.WriteLine(result.ToString());
} 
+1
source

All Articles