LinQ distinct with custom comparer leaves duplicates

自闭症网瘾萝莉.ら 提交于 2019-11-30 19:04:54
SLaks

Your problem is that you didn't implement IEqualityComparer correctly.

When you implement IEqualityComparer<T>, you must implement GetHashCode so that any two equal objects have the same hashcode.

Otherwise, you will get incorrect behavior, as you're seeing here.

You should implement GetHashCode as follows: (courtesy of this answer)

public int GetHashCode(List<SupplierCategory> obj) {
    int hash = 17;

    foreach(var value in obj)
        hash = hash * 23 + obj.GetHashCode();

    return hash;
}

You also need to override GetHashCode in SupplierCategory to be consistent. For example:

public override int GetHashCode() {
    int hash = 17;
    hash = hash * 23 + Name.GetHashCode();
    hash = hash * 23 + Parent.GetHashCode();
    return hash;
}

Finally, although you don't need to, you should probably override Equals in SupplierCategory and make it call the Equals method you implemented for IEquatable.

Actually, this issue is even covered in documentation: http://msdn.microsoft.com/en-us/library/bb338049.aspx.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!