IEqualityComparer GetHashCode being called but Equals not

前端 未结 4 890
暖寄归人
暖寄归人 2020-12-10 03:47

I have two lists that I am trying to compare. So I have created a class that implements the IEqualityComparer interface, please see below in the bottom section

4条回答
  •  佛祖请我去吃肉
    2020-12-10 04:12

    Your Equals and GetHashCode implementations should involve the exact same set of properties; they do not.

    In more formal terms, GetHashCode must always return the same value for two objects that compare equal. With your current code, two objects that differ only in the Ret_USD value will always compare equal but are not guaranteed to have the same hash code.

    So what happens is that LINQ calls GetHashCode on two objects you consider equal, gets back different values, concludes that since the values were different the objects cannot be equal so there's no point at all in calling Equals and moves on.

    To fix the problem, either remove the Ret_USD factor from GetHashCode or introduce it also inside Equals (whatever makes sense for your semantics of equality).

提交回复
热议问题