为什么没有LINQ的方法由predicate返回不同的值? [英] Why is there no Linq method to return distinct values by a predicate?
问题描述
我想在列表中的不同的值,而不是由标准相等比较。
I want to get the distinct values in a list, but not by the standard equality comparison.
我想要做的是这样的:
return myList.Distinct( (x, y) => x.Url == y.Url );
我不能,有一个在LINQ的没有扩展方法,将做到这一点 - 只有一个接受一个的IEqualityComparer
我可以围绕它破解这个:
I can hack around it with this:
return myList.GroupBy( x => x.Url ).Select( g => g.First() );
但似乎混乱。它也并不完全做同样的事情 - 因为我有一个关键的我只能在这里使用它
But that seems messy. It also doesn't quite do the same thing - I can only use it here because I have a single key.
我也可以添加自己的:
public static IEnumerable<T> Distinct<T>(
this IEnumerable<T> input, Func<T,T,bool> compare )
{
//write my own here
}
不过,这似乎相当喜欢写东西,应该在那里摆在首位。
But that does seem rather like writing something that should be there in the first place.
谁知道为什么这种方法是不是有?
Anyone know why this method isn't there?
我缺少的东西吗?
推荐答案
这很烦人,肯定。这也是我的MoreLINQ项目的一部分,我必须在某种程度上给予一些关注,:)还有许多其他的操作作用在投影的时候,却在返回原来这是有意义的 - MaxBy和MinBy映入脑海
It's annoying, certainly. It's also part of my "MoreLINQ" project which I must pay some attention to at some point :) There are plenty of other operations which make sense when acting on a projection, but returning the original - MaxBy and MinBy spring to mind.
正如你所说的,它很容易写的 - 尽管我preFER名DistinctBy来匹配排序依据等等。这里是我的实现,如果你有兴趣:
As you say, it's easy to write - although I prefer the name "DistinctBy" to match OrderBy etc. Here's my implementation if you're interested:
public static IEnumerable<TSource> DistinctBy<TSource, TKey>
(this IEnumerable<TSource> source,
Func<TSource, TKey> keySelector)
{
return source.DistinctBy(keySelector,
EqualityComparer<TKey>.Default);
}
public static IEnumerable<TSource> DistinctBy<TSource, TKey>
(this IEnumerable<TSource> source,
Func<TSource, TKey> keySelector,
IEqualityComparer<TKey> comparer)
{
if (source == null)
{
throw new ArgumentNullException("source");
}
if (keySelector == null)
{
throw new ArgumentNullException("keySelector");
}
if (comparer == null)
{
throw new ArgumentNullException("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;
}
}
}
这篇关于为什么没有LINQ的方法由predicate返回不同的值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!