IEqualityComparer GetHashCode being called but Equals not

前端 未结 4 871
暖寄归人
暖寄归人 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

    Rewrite you GetHashCode implementation like this, to match the semantics of your Equals implementation.

    public int GetHashCode(FactorPayoffs obj)
    {
        unchecked
        {
                int hash = 17;
                hash = hash * 23 + obj.dtPrice.GetHashCode();
                hash = hash * 23 + obj.dtPrice_e.GetHashCode();
                if (obj.Factor != null)
                {
                    hash = hash * 23 + obj.Factor.GetHashCode();
                }
    
                if (obj.FactorGroup != null)
                {
                    hash = hash * 23 + obj.FactorGroup.GetHashCode();
                }
    
                return hash;
        }
    }
    

    Note, you should use unchecked because you don't care about overflows. Additionaly, coalescing to string.Empty is pointlessy wasteful, just exclude from the hash.

    See here for the best generic answer I know,

提交回复
热议问题