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.

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

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;