转载:
只可惜linq默认不支持.Distinct(p => p.ID);
试想如果能写成下面的样子,是不是更简单优雅:
var p1 = products.Distinct(p => p.ID);var p2 = products.Distinct(p => p.Name);
使用一个简单的 lambda 作为参数,也符合 Linq 一贯的风格。
扩展方法:
public static IEnumerableDistinct (this IEnumerable source, Func keySelector, IEqualityComparer comparer = EqualityComparer .Default){ return source.Distinct(new CommonEqualityComparer (keySelector, comparer));}
using System;using System.Collections.Generic;using System.Runtime.CompilerServices;using System.Linq;public class CommonEqualityComparer: IEqualityComparer { private Func keySelector; private IEqualityComparer comparer; public CommonEqualityComparer(Func keySelector, IEqualityComparer comparer) { this.keySelector = keySelector; this.comparer = comparer; } public CommonEqualityComparer(Func keySelector) : this(keySelector, EqualityComparer .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)); }}