Skip to content

Instantly share code, notes, and snippets.

@ngbrown
Created January 27, 2016 21:44
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ngbrown/f7841883cb9c692a749c to your computer and use it in GitHub Desktop.
Save ngbrown/f7841883cb9c692a749c to your computer and use it in GitHub Desktop.
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