Reputation:
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
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