转载:http://www.cnblogs.com/ldp615/archive/2011/08/01/distinct-entension.html
只可惜linq默认不支持.Distinct(p => p.ID);
试想如果能写成下面的样子,是不是更简单优雅:
var p1 = products.Distinct(p => p.ID); var p2 = products.Distinct(p => p.Name);
使用一个简单的 lambda 作为参数,也符合 Linq 一贯的风格。
扩展方法:
public static IEnumerable<T> Distinct<T, V>(this IEnumerable<T> source, Func<T, V> keySelector, IEqualityComparer<V> comparer = EqualityComparer<V>.Default) { return source.Distinct(new CommonEqualityComparer<T, V>(keySelector, comparer)); }
using System; using System.Collections.Generic; using System.Runtime.CompilerServices; using System.Linq; public class CommonEqualityComparer<T, V> : IEqualityComparer<T> { private Func<T, V> keySelector; private IEqualityComparer<V> comparer; public CommonEqualityComparer(Func<T, V> keySelector, IEqualityComparer<V> comparer) { this.keySelector = keySelector; this.comparer = comparer; } public CommonEqualityComparer(Func<T, V> keySelector) : this(keySelector, EqualityComparer<V>.Default) { } public bool Equals(T x, T y) { return comparer.Equals(keySelector(x), keySelector(y)); } public int GetHashCode(T obj) { return comparer.GetHashCode(keySelector(obj)); } }
时间: 2024-10-11 12:55:09