Created
January 27, 2016 21:44
-
-
Save ngbrown/f7841883cb9c692a749c to your computer and use it in GitHub Desktop.
Generic IEqualityComparer implementation
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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