Icemanind
Icemanind

Reputation: 48686

Comparing 2 lists using Linq

I have 2 lists I am trying to compare. I execute the following and I get a false value returned:

var areIdentical = list1.SequenceEqual(list2, myFileCompare);

That part is working. My lists are NOT equal. The problem is, I'm using the following command to try to find the differences:

var fileDiff = (from file in list1 
                select file).Except(list2, myFileCompare);

My problem is, fileDiff is returning an empty result set. Since I know they are NOT identical, shouldn't I get something returned? Perhaps my query is wrong on this. Any help would be appreciated! By the way, I can post more of my code, if you really need it, however, this should suffice.

Upvotes: 4

Views: 1966

Answers (4)

Branko Dimitrijevic
Branko Dimitrijevic

Reputation: 52107

SequenceEqual cares about sequence (which is kind of hinted in its name ;) ), but Except doesn't.

  • So it is entirely possible that list2 contains same elements as list1, but in different order, so SequenceEqual returns false yet Except returns no elements.
  • It is also possible that list2 is a proper super-set of the list1, in which case SequenceEqual returns false regardless of order, and Except still returns no elements.

If you want to work with set operations, you'll probably be better off using some set-like container such as HashSet or SortedSet directly. In your case, you might be interested in HashSet.SetEquals and/or HashSet.ExceptWith.

Upvotes: 0

Reddog
Reddog

Reputation: 15579

If you are after the symmetric difference (all differences between either list, ordering is not important) then you could use the following which will be heavy on the computation but should do the trick:

var fileDiff = list1.Union(list2).Except(list1.Intersect(list2));

Or (as per Jon Skeet's answer):

var fileDiff = list1.Except(list2).Union(list2.Except(list1));

I'll leave it to the rest of the community to show you a more efficient way to do it... But this is the most obvious "linq" way that I can think of...

Upvotes: 1

Jon Skeet
Jon Skeet

Reputation: 1499740

You wouldn't get anything if:

  • list2 contained everything in list1 but also extra items
  • the ordering was different

Assuming you don't care about the ordering, you can use:

var extraItemsInList2 = list2.Except(list1);
var extraItemsInList1 = list1.Except(list2);

If you do care about the order, you'll need to work out exactly how you want the differences to be represented.

Upvotes: 6

Justin Niessner
Justin Niessner

Reputation: 245389

SequenceEqual() will return true only if the elements as well as the element sequence is the same.

Except() will compare only the elements, not the sequence.

Your two lists obviously have different sequences but, judging by the behavior you've posted, I'm guessing they both contain the same elements.

Upvotes: 1

Related Questions