Visual studio feeds

All Visual Studio blogs in one place

Subscribe

Enter your email address:

Delivered by FeedBurner

Increase your website traffic with Attracta.com

Google+

Contact

Email:
Subject:
Message:
Anti-spam: How many eyes has a typical person?

Follow us on FB

Search

Generic IEqualityComparer

AddThis Social Bookmark Button
A generic equality comparer that takes a property expression or a comparison Func 

public class GenericComparer : IEqualityComparer where T : class
{
private readonly Func comparerExpression;
private readonly string propertyName;
public GenericComparer(Func comparerExpression)
{
this.comparerExpression = comparerExpression;
}
public GenericComparer(Expression> 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();             }         }

 

Home : Blog List : .Nettuce : Generic IEqualityComparer