1234567891011121314151617181920212223242526272829303132333435363738394041 |
- using System;
- using System.Collections.Generic;
- using System.Linq.Expressions;
- using System.Text;
- namespace Dfs.WayneChina.SpsDataCourier
- {
- /// <summary>
- /// Taken from the link below:
- /// https://stackoverflow.com/questions/3189861/pass-a-lambda-expression-in-place-of-icomparer-or-iequalitycomparer-or-any-singl
- /// </summary>
- /// <typeparam name="T"></typeparam>
- /// <typeparam name="TKey"></typeparam>
- public class GenericComparer<T, TKey> : IComparer<T>, IEqualityComparer<T>
- {
- private readonly Expression<Func<T, TKey>> _KeyExpr;
- private readonly Func<T, TKey> _CompiledFunc;
-
- // Constructor
- public GenericComparer(Expression<Func<T, TKey>> getKey)
- {
- _KeyExpr = getKey;
- _CompiledFunc = _KeyExpr.Compile();
- }
- public int Compare(T obj1, T obj2)
- {
- return Comparer<TKey>.Default.Compare(_CompiledFunc(obj1), _CompiledFunc(obj2));
- }
- public bool Equals(T obj1, T obj2)
- {
- return EqualityComparer<TKey>.Default.Equals(_CompiledFunc(obj1), _CompiledFunc(obj2));
- }
- public int GetHashCode(T obj)
- {
- return EqualityComparer<TKey>.Default.GetHashCode(_CompiledFunc(obj));
- }
- }
- }
|