Home > front end >  LINQ SequenceEqual returns false but comparing using Except gives different result
LINQ SequenceEqual returns false but comparing using Except gives different result

Time:01-13

I have two lists that I believe to be equal and in same sequence, but when I run SequenceEqual() it is returning false. See below for pseudo example:

// For brevity’s sake assume the two-list data is as follows
List<string> list1 = new List<string> {"1", "2", "3"};
List<string> list2 = new List<string> {"1", "2", "3"};

list1.SequenceEqual(list2); // returning false
list1.Except(list2).Count(); // returning 0
list2.Except(list1).Count(); // returning 0

In reality my list data is much larger (~ 8000 items), but I am confused why I would get 0 for both Except().Count() yet false for SequenceEqual()?

Edit: Added Count to the Except examples.

CodePudding user response:

You do different comparisons. As for Except it

  • Removes duplicates
  • Doesn't take order of items into account
  • Ignores items which are in the second argument if they are not present in the first

that's why

// Duplicated "2" will be ignored
List<string> list1 = new List<string>() { "1", "2", "3", "2" };
// Duplicated "3" will be ignored
// Order doesn't matter
// "7777777" will be ignored
List<string> list2 = new List<string>() { "3", "3", "1", "2", "7777777"};

// 0; since all items within list1 - "1", "2", "3"
// are in the list2, duplicates ignored
int count = list1.Except(list2).Count();

When SequenceEqual returns true if and only if sequences are equal order and duplicates matter. In the example above SequenceEqual returns false since list1.Count != list2.Count, list1[0] != list2[0] etc.

  • Related