您想要的是能够基于选择器从序列中获取不同的项目,但保留原始序列中的项目而不是选择器的结果。这通常被命名为DistinctBy
. MoreLinq 有一个实现,它(稍作修改)是:
public static IEnumerable<TSource> DistinctBy<TSource, TKey>(this IEnumerable<TSource> source,
Func<TSource, TKey> keySelector)
{
return source.DistinctBy(keySelector, null);
}
public static IEnumerable<TSource> DistinctBy<TSource, TKey>(this IEnumerable<TSource> source,
Func<TSource, TKey> keySelector, IEqualityComparer<TKey> comparer)
{
return DistinctByImpl(source, keySelector, comparer);
}
private static IEnumerable<TSource> DistinctByImpl<TSource, TKey>(IEnumerable<TSource> source,
Func<TSource, TKey> keySelector, IEqualityComparer<TKey> comparer)
{
HashSet<TKey> knownKeys = new HashSet<TKey>(comparer);
foreach (TSource element in source)
{
if (knownKeys.Add(keySelector(element)))
{
yield return element;
}
}
}
使用它,连同将行转换回表的CopyToDataTable方法,您现在可以执行以下操作:
var distinctTable = datatable.AsEnumerable()
.DistinctBy(row => row.Field<string>("Employee"))
.CopyToDataTable();