1. DistinctEqualityComparer.cs
public class DistinctEqualityComparer<T, V> : IEqualityComparer<T>
{
private Func<T, V> keySelector;
public DistinctEqualityComparer(Func<T, V> keySelector)
{
this.keySelector = keySelector;
}
public bool Equals(T x, T y)
{
return EqualityComparer<V>.Default.Equals(keySelector(x), keySelector(y));
}
public int GetHashCode(T obj)
{
return EqualityComparer<V>.Default.GetHashCode(keySelector(obj));
}
}
2. DistinctExtensions.cs
public static class DistinctExtensions
{
public static IEnumerable<T> Distinct<T, V>(this IEnumerable<T> source, Func<T, V> keySelector)
{
return source.Distinct(new DistinctEqualityComparer<T, V>(keySelector));
}
}
3. Program.cs
class Program
{
static void Main(string[] args)
{
List<Person> personList = new List<Person>(){
new Person(){Id = 1, Name = "Steven"},
new Person(){Id = 2, Name = "Steven"},
new Person(){Id = 3, Name = "Steven"},
new Person(){Id = 3, Name = "Steven"},
};
List<Person> delegateList = personList.Distinct(x => x.Id).ToList();
}
}