sabato 6 ottobre 2012

Equality Comparer with Lambda

Today, it's normal to write code with LINQ and Lambda Expressions.
But when you need to use IEqualityComparer, it's not possibile to use a lambda predicate.
The Interface needs a class, then you have to create a new type that inherit from IEqualityComparer.

You can use this workaround:
public class EqualityComparer<T> : IEqualityComparer<T>
   private Func<T, T, bool> _fnEquals;
   private Func<T, int> _fnGetHashCode;
   public EqualityComparer(Func<T, T, bool> fnEquals, Func<T, int> fnGetHashCode)
      _fnEquals = fnEquals;
      _fnGetHashCode = fnGetHashCode;
   public bool Equals(T x, T y)
      return _fnEquals(x, y);
   public int GetHashCode(T obj)
      return _fnGetHashCode(obj);

The simple usage is:

Dictionary<int, string> d = new Dictionary<int, string>() { { 1, "a" }, { 2, "a" }, { 3, "b" } };

var d2 = d.Distinct(new EqualityComparer<KeyValuePair<int, string>>((kvp1, kvp2) => kvp1.Value == kvp2.Value, kvp => kvp.Value.GetHashCode()));

Nessun commento:

Posta un commento