Being somewhat lazy about implementing lots of IEqualityComparers, and given that I couldn\'t easily edit class implementations of object being compared, I went with the fol
If a common use-case is comparing objects according to one of their properties, you could add an additional constructor and implement and call it like this:
public GenericEqualityComparer(Func projection)
{
compareFunction = (t1, t2) => projection(t1).Equals(projection(t2));
hashFunction = t => projection(t).GetHashCode();
}
var comaparer = new GenericEqualityComparer( o => o.PropertyToCompare);
This will automatically use the hash as implemented by the property.
EDIT: a more efficient and robust implementation inspired my Marc's comments:
public static GenericEqualityComparer Create(Func projection)
{
return new GenericEqualityComparer(
(t1, t2) => EqualityComparer.Default.Equals( projection(t1), projection(t2)),
t => EqualityComparer.Default.GetHashCode(projection(t)));
}
var comparer = GenericEqualityComparer.Create( o => o.PropertyToCompare);