How to remove duplicates from collection using IEqualityComparer, LinQ Distinct

前端 未结 6 1857
梦如初夏
梦如初夏 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: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 coll = 
     Employeecollection.DistinctBy(employee => new {employee.fName, employee.lName});
    

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

提交回复
热议问题