LinQ distinct with custom comparer leaves duplicates

后端 未结 2 1411
情话喂你
情话喂你 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<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.

    0 讨论(0)
  • 2021-01-04 23:11

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

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