问题描述
让我说这个:
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" });
现在,当我这样做时:
list = list.Distinct().Tolist();
它显然返回4个元素.我想要一个方法,该方法将比较我在类中拥有的所有数据,并返回唯一的元素,以检查类的每个属性.我需要编写自己的比较器,还是内置的东西可以这种方式工作?
It obviously returns 4 elements. I would like a method, that compares all the data i have in class, and returns unique elements, something that checks every property of the class. Do i need to write my own comparer, or is there something that is built-in that works this way?
推荐答案
您必须重写Foo.Equals
(随后是Foo.GetHashCode
)以显式比较每个字段.否则,它将使用默认实现Object.Equals
(ReferenceEquals
).
You have to override Foo.Equals
(and subsequently Foo.GetHashCode
) to explicitly compare each field. Otherwise it will use the default implementation, Object.Equals
(ReferenceEquals
).
或者,您可以将IEqualityComparer
显式传递给Distinct()
方法.
Or, you can explicitly pass an IEqualityComparer
to the Distinct()
method.
请注意,尽管使用匿名类确实会返回3个元素.根据您要使用Foo
的位置以及所需的编译时类型安全性,可以执行以下操作:
Note though that using anonymous classes does return 3 elements. Depending on where you want to use Foo
and how much compile-time type safety you need, you could do:
var list = new List<dynamic>();
list.Add(new { id = Guid.Empty, description = "empty" });
list.Add(new { id = Guid.Empty, description = "empty" });
list.Add(new { id = Guid.NewGuid(), description = "notempty" });
list.Add(new { id = Guid.NewGuid(), description = "notempty2" });
list = list.Distinct().ToList(); //3 elements selected
这篇关于Distinct()如何工作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!