使用委托的相等比较器对LINQ的鲜明的() [英] Use a delegate for the equality comparer for LINQ's Distinct()
问题描述
我有一个使用我自己的自定义比较,这样的LINQ鲜明()语句:
I have a LINQ Distinct() statement that uses my own custom comparer, like this:
class MyComparer<T> : IEqualityComparer<T> where T : MyType
{
public bool Equals(T x, T y)
{
return x.Id.Equals(y.Id);
}
public int GetHashCode(T obj)
{
return obj.Id.GetHashCode();
}
}
...
var distincts = bundle.GetAllThings.Distinct(new MyComparer<MySubType>());
这是所有罚款和花花公子和作品,因为我想要的。出于好奇,我需要确定自己的Comparer,或者我可以与代理人代替它呢?我想我应该可以做这样的事情:
This is all fine and dandy and works as I want. Out of curiosity, do I need to define my own Comparer, or can I replace it with a delegate? I thought I should be able to do something like this:
var distincts = bundle.GetAllThings.Distinct((a,b) => a.Id == b.Id);
但是,这并不编译。是否有一个巧妙的方法?
But this doesn't compile. Is there a neat trick?
推荐答案
分明需要一个的IEqualityComparer作为第二个参数,所以你需要的IEqualityComparer。这不是太难做一个通用的一个,将采取委托,虽然。当然,这有可能已经被一些地方,如MoreLINQ实施了其他的答案中的一个建议。
Distinct takes an IEqualityComparer as the second argument, so you will need an IEqualityComparer. It's not too hard to make a generic one that will take a delegate, though. Of course, this has probably already been implemented in some places, such as MoreLINQ suggested in one of the other answers.
您可以实现它是这样的:
You could implement it something like this:
public static class Compare
{
public static IEnumerable<T> DistinctBy<T, TIdentity>(this IEnumerable<T> source, Func<T, TIdentity> identitySelector)
{
return source.Distinct(Compare.By(identitySelector));
}
public static IEqualityComparer<TSource> By<TSource, TIdentity>(Func<TSource, TIdentity> identitySelector)
{
return new DelegateComparer<TSource, TIdentity>(identitySelector);
}
private class DelegateComparer<T, TIdentity> : IEqualityComparer<T>
{
private readonly Func<T, TIdentity> identitySelector;
public DelegateComparer(Func<T, TIdentity> identitySelector)
{
this.identitySelector = identitySelector;
}
public bool Equals(T x, T y)
{
return Equals(identitySelector(x), identitySelector(y));
}
public int GetHashCode(T obj)
{
return identitySelector(obj).GetHashCode();
}
}
}
它给你的语法:
source.DistinctBy(a => a.Id);
或者,如果你觉得它更清晰是这样的:
Or, if you feel it's clearer this way:
source.Distinct(Compare.By(a => a.Id));
这篇关于使用委托的相等比较器对LINQ的鲜明的()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!