How to implement IEqualityComparer to return distinct values?

An EqualityComparer is not the way to go – it can only filter your result set in memory eg: var objects = yourResults.ToEnumerable().Distinct(yourEqualityComparer); You can use the GroupBy method to group by IDs and the First method to let your database only retrieve a unique entry per ID eg: var objects = yourResults.GroupBy(o => o.Id).Select(g … Read more

writing a custom comparer for linq groupby

The grouping algorithm (and I think all LINQ methods) using an equality comparer always first compares hash codes and only executes Equals if two hash codes are equal. You can see that if you add tracing statements in the equality comparer: class PointComparer : IEqualityComparer<Point> { public bool Equals(Point a, Point b) { Console.WriteLine(“Equals: point … Read more

IEqualityComparer for SequenceEqual

There is no such comparer in .NET Framework, but you can create one: public class IEnumerableComparer<T> : IEqualityComparer<IEnumerable<T>> { public bool Equals(IEnumerable<T> x, IEnumerable<T> y) { return Object.ReferenceEquals(x, y) || (x != null && y != null && x.SequenceEqual(y)); } public int GetHashCode(IEnumerable<T> obj) { // Will not throw an OverflowException unchecked { return obj.Where(e … Read more

What problem does IStructuralEquatable and IStructuralComparable solve?

All types in .NET support the Object.Equals() method which, by default, compares two types for reference equality. However, sometimes, it also desirable to be able to compare two types for structural equality. The best example of this is arrays, which with .NET 4 now implement the IStructuralEquatable interface. This makes it possible to distinguish whether … Read more

How to use the IEqualityComparer

Your GetHashCode implementation always returns the same value. Distinct relies on a good hash function to work efficiently because it internally builds a hash table. When implementing interfaces of classes it is important to read the documentation, to know which contract you’re supposed to implement.1 In your code, the solution is to forward GetHashCode to … Read more