Create a gist now

Instantly share code, notes, and snippets.

What would you like to do?
Generic IEqualityComparer implementation
using System;
using System.Collections.Generic;
using System.Linq;
namespace Helpers
{
public class GenericEqualityComparer
{
public static IEqualityComparer<T> Create<T>(params Func<T, object>[] Param1)
{
return new Impl<T>(Param1);
}
private class Impl<T> : IEqualityComparer<T>
{
private readonly Func<T, object>[] accessors;
public Impl(Func<T, object>[] accessors)
{
this.accessors = accessors;
}
public bool Equals(T x, T y)
{
return this.accessors.All(a => object.Equals(a(x), a(y)));
}
public int GetHashCode(T obj)
{
return this.accessors.Aggregate(17, (s, a) =>
{
unchecked // Overflow is fine, just wrap
{
return s*23 + a(obj).GetHashCode();
}
});
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment