GenericComparer.cs 1.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq.Expressions;
  4. using System.Text;
  5. namespace Dfs.WayneChina.SpsDataCourier
  6. {
  7. /// <summary>
  8. /// Taken from the link below:
  9. /// https://stackoverflow.com/questions/3189861/pass-a-lambda-expression-in-place-of-icomparer-or-iequalitycomparer-or-any-singl
  10. /// </summary>
  11. /// <typeparam name="T"></typeparam>
  12. /// <typeparam name="TKey"></typeparam>
  13. public class GenericComparer<T, TKey> : IComparer<T>, IEqualityComparer<T>
  14. {
  15. private readonly Expression<Func<T, TKey>> _KeyExpr;
  16. private readonly Func<T, TKey> _CompiledFunc;
  17. // Constructor
  18. public GenericComparer(Expression<Func<T, TKey>> getKey)
  19. {
  20. _KeyExpr = getKey;
  21. _CompiledFunc = _KeyExpr.Compile();
  22. }
  23. public int Compare(T obj1, T obj2)
  24. {
  25. return Comparer<TKey>.Default.Compare(_CompiledFunc(obj1), _CompiledFunc(obj2));
  26. }
  27. public bool Equals(T obj1, T obj2)
  28. {
  29. return EqualityComparer<TKey>.Default.Equals(_CompiledFunc(obj1), _CompiledFunc(obj2));
  30. }
  31. public int GetHashCode(T obj)
  32. {
  33. return EqualityComparer<TKey>.Default.GetHashCode(_CompiledFunc(obj));
  34. }
  35. }
  36. }