Geeks With Blogs
.Nettuce Code Salad
A generic equality comparer that takes a property to compare or a comparison function
public class GenericComparer<T> : IEqualityComparer<T> where T : class
    {
        readonly Func<T, object> propertyToCompare;
        readonly Func<T, T, bool> comparisonFunction;
 
        public GenericComparer(Func<T, T, bool> comparisonFunction)
        {
            this.comparisonFunction = comparisonFunction;
        }
 
        public GenericComparer(Func<T, object> propertyToCompare)
        {
            this.propertyToCompare = propertyToCompare;
        }
 
        public bool Equals(T x, T y)
        {
            return comparisonFunction == null ? propertyToCompare(x) == propertyToCompare(y) : comparisonFunction(x, y);
        }
 
        public int GetHashCode(T obj)
        {
            return obj.ToString().GetHashCode();
        }
    }

Here's an example as requested. A simple employee class and some tests to demonstrate custom equality:

    public class Employee
    {
        public string Name { getset; }
        public string Department { getset; }
        public string Barcode { getset; }
    }
        var employees1 = new[] {new Employee {Name = "Bob", Department = "Accounts", Barcode = "A123456"}};
        var employees2 = new[] {new Employee {Name = "Terry", Department = "Accounts", Barcode = "B123456"}};
        Assert.IsFalse(employees1.SequenceEqual(employees2));
       Assert.IsTrue(employees1.SequenceEqual(employees2, new GenericComparer<Employee>(x => x.Department)));
       Assert.IsTrue(employees1.SequenceEqual(employees2, new GenericComparer<Employee>((x, y) => x.Barcode.Substring(1) == y.Barcode.Substring(1))));
Posted on Tuesday, January 11, 2011 11:43 PM | Back to top


Comments on this post: Generic IEqualityComparer

# re: Generic IEqualityComparer
Requesting Gravatar...
Can you post a code demonstrating the usage of this custiom comparer?
Left by Anonymous on Feb 11, 2011 9:14 AM

Your comment:
 (will show your gravatar)


Copyright © Jon Canning | Powered by: GeeksWithBlogs.net