Generic IEqualityComparer
Posted
by Nettuce
on Geeks with Blogs
See other posts from Geeks with Blogs
or by Nettuce
Published on Tue, 11 Jan 2011 23:43:26 GMT
Indexed on
2011/01/11
23:54 UTC
Read the original article
Hit count: 170
Filed under:
A generic equality comparer that takes a property expression or a comparison Func
public class GenericComparer<T> : IEqualityComparer<T> where T : class { private readonly Func<T, T, bool> comparerExpression; private readonly string propertyName; public GenericComparer(Func<T, T, bool> comparerExpression) { this.comparerExpression = comparerExpression; } public GenericComparer(Expression<Func<T, object>> propertyExpression) { propertyName = (propertyExpression.Body is UnaryExpression ? (MemberExpression)((UnaryExpression)propertyExpression.Body).Operand : (MemberExpression)propertyExpression.Body).Member.Name; } public bool Equals(T x, T y) { return comparerExpression == null ? x.GetType().GetProperty(propertyName).GetValue(x, null).Equals(y.GetType().GetProperty(propertyName).GetValue(y, null)) : comparerExpression.Invoke(x, y); } public int GetHashCode(T obj) { return obj.ToString().GetHashCode(); } }
© Geeks with Blogs or respective owner