Skip to content

Instantly share code, notes, and snippets.

@Vaccano
Created March 17, 2010 22:06
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 Vaccano/335780 to your computer and use it in GitHub Desktop.
Save Vaccano/335780 to your computer and use it in GitHub Desktop.
/// <summary>
/// Useful for comparing two objects.
/// Example usage:
/// var dropOffComparer = new LambdaComparer<ConsolidationDropOff>((x, y) => x.Id == y.Id);
/// dropOffs.Contains(dropOff, dropOffComparer);
/// </summary>
/// <typeparam name="T"></typeparam>
public class LambdaComparer<T> : IEqualityComparer<T>
{
Func<T, T, bool> _comparer;
Func<T, int> _hash;
public LambdaComparer(Func<T, T, bool> comparer)
{
_comparer = comparer;
_hash = t => t.GetHashCode();
}
public LambdaComparer(Func<T, T, bool> comparer, Func<T, int> hash)
{
_comparer = comparer;
_hash = hash;
}
public bool Equals(T x, T y)
{
return _comparer(x, y);
}
public int GetHashCode(T obj)
{
return _hash(obj);
}
}
public static class SequenceExtensions
{
public static bool SequenceEqual<T>(this IEnumerable<T> first, IEnumerable<T> second, Func<T, T, bool> comparer)
{
return first.SequenceEqual(second, new LambdaComparer<T>(comparer));
}
public static bool SequenceEqual<T>(this IEnumerable<T> first, IEnumerable<T> second, Func<T, T, bool> comparer, Func<T, int> hash)
{
return first.SequenceEqual(second, new LambdaComparer<T>(comparer, hash));
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment