Why does the SequenceEqual for List <T> return false?

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

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 it works great

 bool equal = list1.SequenceEqual(list2); 

and returns true ;

but when I have some method that returns a 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 as follows:

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

and then just check it out

 bool equal = list1.SequenceEqual(list2); 

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

+4
source share
3 answers

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

Your Sentence class should override Equals and GetHashCode , at least at this point your SequenceEquals should work again.

+8
source

Since MSDN is listed here:

Determines whether two sequences are equal by comparing items using the default comparison for their type.

Sentence in your case is the default reference type Equals and GetHashCode , which means that it will use reference equality for each element.

You can always use overload which accepts IEqualityComparer

+9
source

You create two new instances of the sentence each time you call Getall() . When comparing items in a list, SequenceEqual will use the default equalizer, which basically just checks that they reference the sme object: they don’t do this, so they are different.

What you can do is override the Equal() and == operators in Sequence to check if other properties are equal (e.g. Text and Order).

Alternatively, you can write IEqualityComparer<Sequence> and pass it to SequenceEqual

0
source

All Articles