score:104

Accepted answer

forget iequalitycomparer and just use linq directly:

employeecollection.groupby(x => new{x.fname, x.lname}).select(g => g.first());

score:-1

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.

score:0

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

score:3

the hashcode implementation is not correct:

public override int gethashcode()
{
    return 13 * fname.gethashcode() + 7 * lname.gethashcode();
}

score:5

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.

score:5

here is a good tutorial

    public int gethashcode(employe obj)
    {
        return obj.fname.gethashcode() ^ obj.lname.gethashcode();
    }

Related Query