How to remove duplicates from collection using IEqualityComparer, LinQ Distinct

前端 未结 6 1844
梦如初夏
梦如初夏 2020-12-05 04:36

I am unable to remove the duplicates from collection , i have implemented IEqualityComparer for the class Employee still i am not getting the output

static v         


        
相关标签:
6条回答
  • 2020-12-05 04:51

    Also it looks like your comparing by reference instead of content, hence the compare function doesn't work.

    change it to use .Equals() instead of == and it should work. example below:

    #region IEqualityComparer<pcf> Members
    
    public bool Equals(Employe x, Employe y)
    {
        if (x.fName.Equals(y.fName) && x.lName.Equals(y.lName))
        {
            return true;
        }
    
        return false;
    }
    
    public int GetHashCode(Employe obj)
    {
        return obj.GetHashCode();
    }
    
    #endregion
    
    0 讨论(0)
  • 2020-12-05 04:53

    You need to override GetHashCode method in your Employee. You haven't done this. One example of a good hashing method is given below: (generated By ReSharper)

    public override int GetHashCode()
    {
        return ((this.fName != null ? this.fName.GetHashCode() : 0) * 397) ^ (this.lName != null ? this.lName.GetHashCode() : 0);
    }
    

    now after Distinct is called, foreach loop prints:

    abc   def
    lmn   def
    

    In your case you are calling object's class GetHashCode, which knows nothing about internal fields.

    One simple note, MoreLINQ contains DistinctBy extension method, which allows you to do:

    IEnumerable<Employe> coll = 
     Employeecollection.DistinctBy(employee => new {employee.fName, employee.lName});
    

    Anonymous objects have correct implementation for both GetHashCode and Equals methods.

    0 讨论(0)
  • 2020-12-05 04:53
    public int GetHashCode(Employe obj)
    {
        return obj.GetHashCode();
    }
    

    For this method, return a hashcode of the properties that you are comparing for equality, instead of the object itself. Comparing the hashcode of the objects will always be false, so your list will never be filtered for duplicates.

    0 讨论(0)
  • 2020-12-05 04:55

    Here is a good tutorial

        public int GetHashCode(Employe obj)
        {
            return obj.fname.GetHashCode() ^ obj.lname.GetHashCode();
        }
    
    0 讨论(0)
  • 2020-12-05 05:05

    The hashcode implementation is not correct:

    public override int GetHashCode()
    {
        return 13 * fName.GetHashCode() + 7 * lName.GetHashCode();
    }
    
    0 讨论(0)
  • 2020-12-05 05:06

    Forget IEqualityComparer and just use Linq directly:

    EmployeeCollection.GroupBy(x => new{x.fName, x.lName}).Select(g => g.First());
    
    0 讨论(0)
提交回复
热议问题