Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the easiest way to seeing if there are any matches across a few 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 quickest way to return a list of DateTime that exist in all 3 of the lists. Is there some LINQ statement?

like image 729
leora Avatar asked Feb 16 '13 17:02

leora


2 Answers

List<DateTime> common = list1.Intersect(list2).Intersect(list3).ToList();
like image 71
Lee Avatar answered Oct 19 '22 04:10

Lee


HashSet<DateTime> common = new HashSet<DateTime>( list1 );
common.IntersectWith( list2 );
common.IntersectWith( list3 );

The HashSet class is more efficient for such tasks than using Enumerable.Intersect.

Update: make sure all your values are of the same DateTimeKind.

like image 37
Soonts Avatar answered Oct 19 '22 06:10

Soonts