你想要的是能够基于选择器从序列中获得不同的项目,但是保留项目与原始序列而不是选择器的结果。这通常被命名为DistinctBy
。 MoreLinq has an implementation,其中(稍作修改)是:
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();
为什么不能使用var?根据你的样本,它应该被视为IList?您的所有方法签名必须看起来像Method(IList distinctValues){} ... –
nakchak
2013-05-09 14:26:25
@nakchak结果将是一个'List <{anonymous type}>'。 '实体'是_property_,而不是_class_。 – 2013-05-09 14:29:53
好点,那就说为什么要烦扰一个匿名类,如果它只有一个字符串属性呢? – nakchak 2013-05-09 14:33:06