我知道有两种方法可以从支持显式比较的对象数组中删除双打:
如何从结构数组中删除双精度数,仅将数组成员与单个字段进行比较?换句话说,如何编写可以由Distinct()使用的谓词.
问候,
好吧,你可以实现IEqualityComparer<T>
挑选该字段并将其用于相等性测试和散列......或者你可以使用MoreLINQDistinctBy
中的那个.
当然,您不必非常依赖MoreLINQ - 您可以非常简单地实现它:
public static IEnumerable<TSource> DistinctBy<TSource, TKey>
(this IEnumerable<TSource> source,
Func<TSource, TKey> keySelector)
{
// TODO: Implement null argument checking :)
HashSet<TKey> keys = new HashSet<TKey>();
foreach (TSource element in source)
{
if (knownKeys.Add(keySelector(element)))
{
yield return element;
}
}
}
Run Code Online (Sandbox Code Playgroud)