Monday, February 7, 2011

ASP.NET LINQ Union Distinct not working

Using Union(....).Distinct() not producing a distinct list when unioning a list of complex objects.

CAUSE:
Union() and Distinct() don't know which member of the object to use in their comparisons.

SOLUTION:
1. - IEqualityComparer needs to be defined to specify what fields of the object to compare:

public class MyComplexObjectComparer : IEqualityComparer
{
public bool Equals(complexObject a, complexObject b)
{
return a.Id == b.Id;
}

public int GetHashCode(complexObject obj)
{
return obj.Id.GetHashCode();
}
}

2. - Pass this comparer into the Union:

.Union(lockedout, new MyComplexObjectComparer()).Distinct;


SOURCE:
http://blog.dreamlabsolutions.com/post/2009/06/23/Enumerable-Except-TSource-and-IEqualityComparer-a-little-help.aspx