我有一个 LINQ Distinct() 语句,它使用我自己的自定义比较器,如下所示:
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>());
这一切都很好,而且按照我想要的方式工作。出于好奇,我是否需要定义自己的比较器,或者我可以用委托替换它吗?我想我应该能够做这样的事情:
var distincts = bundle.GetAllThings.Distinct((a,b) => a.Id == b.Id);
但这不能编译。有什么巧妙的技巧吗?
Distinct 将 IEqualityComparer 作为第二个参数,因此您将需要一个 IEqualityComparer。不过,制作一个需要委托的通用模型并不太难。当然,这可能已经在某些地方实现了,例如其他答案之一中建议的 MoreLINQ。
你可以像这样实现它:
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);
或者,如果你觉得这样更清楚:
source.Distinct(Compare.By(a => a.Id));
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)