Generic IEqualityComparer
- by Nettuce
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();
}
}