So .NET 3.0/3.5 provides us with lots of new ways to query, sort, and manipulate data, thanks to all the neat functions supplied with LINQ. Sometimes, I need to compare user-defined types that don’t have a built-in comparison operator. In many cases, the comparison is really simple — something like foo1.key ?= foo2.key. Rather than creating a new IEqualityComparer for the type, can I simply specify the comparison inline using anonymous delegates/lambda functions? Something like:
var f1 = ..., f2 = ...; var f3 = f1.Except( f2, new IEqualityComparer( (Foo a, Foo b) => a.key.CompareTo(b.key) ) );
I’m pretty sure the above doesn’t actually work. I just don’t want to have to make something as ‘heavy’ as a whole class just to tell the program how to compare apples to apples.
My MiscUtil library contains a ProjectionComparer to build an IComparer<T> from a projection delegate. It would be the work of 10 minutes to make a ProjectionEqualityComparer to do the same thing.
EDIT: Here’s the code for ProjectionEqualityComparer:
And here’s a sample use: