Search code examples
c#listcomparison

Why SequenceEqual for List<T> returns false?


Hi I have some problems with sequenceEqual when I have situation like this:

Sentence s1 = new Sentence { Text = "Hi", Order = 1 };
Sentence s2 = new Sentence { Text = "Hello", Order = 2 };
List<Sentence> list1 = new List<Sentence> { s1, s2 };
List<Sentence> list2 = new List<Sentence> { s1, s2 };

and this works fine

bool equal = list1.SequenceEqual(list2);

and returns true;

but when I have some method which returns List<Sentence> for example:

public List<Sentence> Getall()
    {
        Sentence s1 = new Sentence { Text = "Hi", Order = 1 };
        Sentence s2 = new Sentence { Text = "Hello", Order = 2 };

        return new List<Sentence> { s1, s2 };
    }

and use it like this:

List<Sentence> list1 = Getall();
List<Sentence> list2 = Getall();

and then simply, check it

bool equal = list1.SequenceEqual(list2);

it returns 'false', please tell me why? and how to make it work?


Solution

  • Your problem is that one new Sentence { Text = "Hi", Order = 1 } is not equal to another new Sentence { Text = "Hi", Order = 1 }. Although the contents are the same, you have two separate objects, and unless you've designed your class otherwise they are not equal to each other unless they are literally the same objects (as in your first example).

    Your Sentence class needs to override Equals and GetHashCode, at the very least, at which point your SequenceEquals should work again.