Seeing you unmarked the answer, I'm going to take a crack at this, however the answers really are good efforts, but a result of your vague problem definition. Even your comment "If there are any items in either list that do not exist in the other" is a little awkwardly worded. Not trying to grill you, but just keep that in mind. When dealing with set operations you have to take a step back and really think carefully about what you want to accomplish. I'm going to interpret your goal as this, and if this is incorrect, you should update your question with a more clearly defined problem definition:
I want to check and make sure that for every item in myFirstList,
there is an item in mySecondList with the same SomeDate.Date, and vice
versa.
If you are truncating time from a date, then I would speculate there might be cases where there are two items with the same date. If this were not the case, there are easier methods that take approaches such as joining or intersecting the lists and checking that the results have equal Count as the originals(which verifies that all items found a match). The other answers using join or intersect don't quite work, because they use .Any()
which will return true if just one of the items matches, rather than all.
.All
will make sure that all items in one list meet some criteria. In this case, make sure every item has a match in the second list.
bool isListEqual = myFirstList.All(x=>
mySecondList.Select(y=>y.SomeDate.Date).Contains( x.SomeDate.Date) )
isListEqual = isListEqual && mySecondList.All(x=>
myFirstList.Select(y=>y.SomeDate.Date).Contains( x.SomeDate.Date) )
We do it both directions to ensure there are no items in the second list without a matching item in the first.
If we knew there were no duplicates, another approach would be to join the lists and count the results to ensure they match the originals. Or we could simply eliminate duplicates to generate distinct lists. You can also use SetEquals
of hashset, or SequenceEquals
of IEnumerable. SequenceEquals is better if you know your results are already in a particular order.
var firstDates = myFirstList.Select(l=>l.SomeDate.Date).Distinct().OrderBy(d=>d).ToList();
var secondDates = mySecondList.Select(l=>l.SomeDate.Date).Distinct().OrderBy(d=>d).ToList();
bool isListEqual = firstDates.SequenceEqual(secondDates);
I think the most important thing you should take from this, is the approach is dependent on what assumptions you can make about your input data.
This question covers several approaches, and the duplicate it is linked to as well:
Check if two lists are equal