user3857185
user3857185

Reputation:

Using IEqualityComparer and Linq Except gives me the result of list of duplicate ones

I have two list that needs to be compared and should exclude duplicates by their external Id, however the result that I always get is the list of records that have the same external Id in both list.

Code:

public class FooComparer : IEqualityComparer<Foo>
{
    public bool Equals(Foo x, Foo y)
    {
        if (ReferenceEquals(x, y)) return true;

        if (ReferenceEquals(x, null) || ReferenceEquals(y, null))
            return false;

        return x.ExternalId == y.ExternalId;
    }

    public int GetHashCode(Foo foo)
    {
        if (ReferenceEquals(foo, null)) return 0;

        return foo.ExternalId.GetHashCode();
    }
}

var bulkFoos = _bulkFoo.GetBulkFoos();
var fooFromXmlList = Mapper.Map<List<Foo>>(bulkFoos);

var foosWithUniqueId = _fooRepository.GetAllWithExternalId();
var fooWithUniqueIdList = Mapper.Map<List<Foo>>(foosWithUniqueId);

var fooList = fooFromXmlList.Except(fooWithExternalIdList, new FooComparer());

Upvotes: 0

Views: 117

Answers (1)

Lee
Lee

Reputation: 144136

Your GetHashCode implementation should use the same properties as those for equality, however yours uses foo.Id for the hash code and foo.externalId for equality. Change GetHashCode to use externalId:

public int GetHashCode(Foo foo)
{
    if(ReferenceEquals(foo, null)) return 0;
    else return foo.externalId.GetHashCode();
}

Upvotes: 1

Related Questions