Skip to content

Instantly share code, notes, and snippets.

@sean-gilliam
Created January 13, 2019 22:42
Show Gist options
  • Save sean-gilliam/a2a24658a1ac86ad12238db6c3fd9553 to your computer and use it in GitHub Desktop.
Save sean-gilliam/a2a24658a1ac86ad12238db6c3fd9553 to your computer and use it in GitHub Desktop.
Lambda based IEqualityComparer
void Main()
{
List<Person> persons = new List<Person>
{
new Person { Id = 1, Name = "Bob", Location = "AFB" },
new Person { Id = 2, Name = "Alice", Location = "AFB" },
new Person { Id = 3, Name = "Jill", Location = "AFB" },
new Person { Id = 4, Name = "Frank", Location = "AFB" },
new Person { Id = 1, Name = "Mark", Location = "AFB" }
};
var list = persons.Distinct().ToList();
var lambdalist = persons.Distinct((x, y) => x.Id == y.Id).ToList();
Console.WriteLine("Regular Distinct");
foreach(var l in list)
{
Console.WriteLine($"Person :: Id = {l.Id}, Name = {l.Name}, Location = {l.Location}");
}
Console.WriteLine("Lambda Distinct");
foreach(var ll in lambdalist)
{
Console.WriteLine($"Person :: Id = {ll.Id}, Name = {ll.Name}, Location = {ll.Location}");
}
}
public class Person
{
public int Id {get;set;}
public string Name {get;set;}
public string Location {get;set;}
}
public static class Extensions
{
public static IEnumerable<TSource> Distinct<TSource>(this IEnumerable<TSource> enumerable, Func<TSource, TSource, bool> comparer)
{
return enumerable.Distinct(new LambdaComparer<TSource>(comparer));
}
}
public class LambdaComparer<T> : IEqualityComparer<T>
{
private readonly Func<T, T, bool> _lambdaComparer;
private readonly Func<T, int> _lambdaHash;
public LambdaComparer(Func<T, T, bool> lambdaComparer) :
this(lambdaComparer, o => 0)
{
}
public LambdaComparer(Func<T, T, bool> lambdaComparer, Func<T, int> lambdaHash)
{
if (lambdaComparer == null)
throw new ArgumentNullException("lambdaComparer");
if (lambdaHash == null)
throw new ArgumentNullException("lambdaHash");
_lambdaComparer = lambdaComparer;
_lambdaHash = lambdaHash;
}
public bool Equals(T x, T y)
{
return _lambdaComparer(x, y);
}
public int GetHashCode(T obj)
{
return _lambdaHash(obj);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment