Why SequenceEqual for List returns false?

前端 未结 3 1520
忘了有多久
忘了有多久 2020-12-18 00:29

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

Sentence s1 = new Sentence { Text = \"Hi\", Order = 1 };
Sentence s2 = new Senten         


        
相关标签:
3条回答
  • 2020-12-18 01:08

    You are creating two new instances of Sentence every time you call Getall(). When comparing the elements in the list, SequenceEqual will use the default equality comparer, which basically just check that they refer the sme object: they don't, so they are different.

    What you can do is override the Equal() and == operators in Sequence to have equality check other properties (like Text and Order).

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

    0 讨论(0)
  • 2020-12-18 01:13

    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.

    0 讨论(0)
  • 2020-12-18 01:30

    As the MSDN states here:

    Determines whether two sequences are equal by comparing the elements by using the default equality comparer for their type.

    Sentence in your case is a reference type with default Equals and GetHashCode, which means it will be using referential equality for each element.

    You can always use the overload which accepts IEqualityComparer

    0 讨论(0)
提交回复
热议问题