Popular Posts

Saturday, June 11, 2011

Lambda Equality Comparer Extension Method

Here's an extension method that will convert a lambda to an equality comparer:
public static class FuncExtension
{
    private class GenericComparer<T> : EqualityComparer<T>
    {
        private readonly Func<T, T, bool> _lambda;
        private readonly bool _passThroughNulls;
        
        public GenericComparer(Func<T, T, bool> lambda, bool passThroughNulls)
        {
            _lambda = lambda; _passThroughNulls = passThroughNulls;
        }

        public override bool Equals(T x, T y)
        {
            if (!_passThroughNulls)
            {
                if (System.Object.Equals(x, default(T)) || System.Object.Equals(y, default(T)))
                {
                    return System.Object.Equals(x, default(T)) && System.Object.Equals(y, default(T));
                }
            }
            
            return _lambda(x, y);
        }
    
        public override int GetHashCode(T obj)
        {
            return 0;
        }
    }
    
    public static IEqualityComparer<T> ToEqualityComparer<T>(this Func<T, T, bool> lambda, bool passThroughNulls = false)
    {
        return new GenericComparer<T>(lambda, passThroughNulls);
    }
}

Here's an example of how to use it:
Func<SomeClass, SomeClass, bool> compareFunction = (x, y) => x.SomeProperty == y.SomeProperty && x.SomeProperty2 == y.SomeProperty2;
EqualityComparer<SomeClass> comparer = compareFunction.ToEqualityComparer();

No comments:

Post a Comment