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
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
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.
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.
Here is a good tutorial
public int GetHashCode(Employe obj)
{
return obj.fname.GetHashCode() ^ obj.lname.GetHashCode();
}
The hashcode implementation is not correct:
public override int GetHashCode()
{
return 13 * fName.GetHashCode() + 7 * lName.GetHashCode();
}
Forget IEqualityComparer and just use Linq directly:
EmployeeCollection.GroupBy(x => new{x.fName, x.lName}).Select(g => g.First());