Created
December 29, 2015 17:52
-
-
Save collinsauve/b7b5cd0d9a03c7a72546 to your computer and use it in GitHub Desktop.
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
public static class LambdaComparer | |
{ | |
/// <summary> | |
/// Creates an <see cref="IEqualityComparer<T>"/> using the given <paramref name="equalsFunc"/> and a constant <see cref="IEqualityComparer<T>.GetHashCode(T)"/> function. | |
/// </summary> | |
/// <typeparam name="T"></typeparam> | |
/// <param name="equalsFunc">A function to use for <see cref="IEqualityComparer<T>.Equals(T, T)"/></param> | |
/// <returns>An <see cref="IEqualityComparer<T>"/></returns> | |
/// <remarks>Since <see cref="IEqualityComparer<T>.GetHashCode(T)"/> will be constant, this comparer will not perform well on large sets. For performance | |
/// critical code, use <see cref="Create<T>(Func<T, T, bool>, Func<T, int>)"/></remarks> | |
public static IEqualityComparer<T> Create<T>(Func<T, T, bool> equalsFunc) | |
{ | |
return Create(equalsFunc, o => 0); | |
} | |
/// <summary> | |
/// Creates an <see cref="IEqualityComparer<T>"/> using the given <paramref name="equalsFunc"/> and <paramref name="hashCodeFunc"/> | |
/// </summary> | |
/// <typeparam name="T"></typeparam> | |
/// <param name="equalsFunc">A function to use for <see cref="IEqualityComparer<T>.Equals(T, T)"/></param> | |
/// <param name="hashCodeFunc">A function to use for <see cref="IEqualityComparer<T>.GetHashCode(T)"/></param> | |
/// <returns>An <see cref="IEqualityComparer<T>"/></returns> | |
public static IEqualityComparer<T> Create<T>(Func<T, T, bool> equalsFunc, Func<T, int> hashCodeFunc) | |
{ | |
return new LambdaComparer<T>(equalsFunc, hashCodeFunc); | |
} | |
} | |
public class LambdaComparer<T> : IEqualityComparer<T> | |
{ | |
private readonly Func<T, T, bool> _equalsFunc; | |
private readonly Func<T, int> _hashCodeFunc; | |
public LambdaComparer(Func<T, T, bool> equalsFunc, Func<T, int> hashCodeFunc) | |
{ | |
_equalsFunc = equalsFunc; | |
_hashCodeFunc = hashCodeFunc; | |
} | |
public bool Equals(T x, T y) | |
{ | |
return _equalsFunc(x, y); | |
} | |
public int GetHashCode(T obj) | |
{ | |
return _hashCodeFunc(obj); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment