LinQ distinct with custom comparer leaves duplicates

后端 未结 2 1445
情话喂你
情话喂你 2021-01-04 22:39

I\'ve got the following classes:

public class SupplierCategory : IEquatable
{
    public string Name { get; set; }
    public string          


        
2条回答
  •  长情又很酷
    2021-01-04 22:48

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

    When you implement IEqualityComparer, 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 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.

提交回复
热议问题