对象的基础上,LINQ任意键不同的列表 [英] Distinct list of objects based on an arbitrary key in LINQ
本文介绍了对象的基础上,LINQ任意键不同的列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一些对象:
class Foo {
public Guid id;
public string description;
}
var list = new List<Foo>();
list.Add(new Foo() { id = Guid.Empty, description = "empty" });
list.Add(new Foo() { id = Guid.Empty, description = "empty" });
list.Add(new Foo() { id = Guid.NewGuid(), description = "notempty" });
list.Add(new Foo() { id = Guid.NewGuid(), description = "notempty2" });
我想处理此列表以这样的方式使 ID
字段是独一无二的,扔掉非唯一对象(基于ID)。
I would like to process this list in such a way that the id
field is unique, and throw away the non-unique objects (based on id).
我能想出的最好的是:
list = list.GroupBy(i => i.id).Select(g=>g.First()).ToList();
有没有更好的/更好/更快捷的方法来达到同样的效果。
Is there a nicer/better/quicker way to achieve the same result.
推荐答案
一个非常优雅和意图揭示选择是定义上的IEnumerable一个新的扩展方法
A very elegant and intention revealing option is to define a new extension method on IEnumerable
所以,你有:
list = list.Distinct(foo => foo.id).ToList();
和
public static IEnumerable<T> Distinct<T,TKey>(this IEnumerable<T> list, Func<T,TKey> lookup) where TKey : struct {
return list.Distinct(new StructEqualityComparer<T, TKey>(lookup));
}
class StructEqualityComparer<T,TKey> : IEqualityComparer<T> where TKey : struct {
Func<T, TKey> lookup;
public StructEqualityComparer(Func<T, TKey> lookup) {
this.lookup = lookup;
}
public bool Equals(T x, T y) {
return lookup(x).Equals(lookup(y));
}
public int GetHashCode(T obj) {
return lookup(obj).GetHashCode();
}
}
有一个类似的辅助类,可以建立比较对象。 (它需要做的更好的空值处理)
A similar helper class can be built to compare objects. (It will need to do better null handling)
这篇关于对象的基础上,LINQ任意键不同的列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文