简体   繁体   English

为什么此LINQ查询不能按预期工作?

[英]Why doesn't this LINQ query work as expected?

Assume I have a class called MyClass that has two properties (int Id and a string Name). 假设我有一个名为MyClass的类,它具有两个属性(int Id和一个字符串Name)。 I want to populate a List of these MyClass objects from another collection but I want only the unique ones. 我想从另一个集合中填充这些MyClass对象的列表,但我只想要唯一的对象。 This other collection is a 3rd party object that has a property named 'Properties' that is just an array of values, the first two of which correspond to the Id and Name values I care about. 这个另一个集合是一个第三方对象,它具有一个名为“ Properties”的属性,该属性只是一个值数组,其中前两个对应于我关心的Id和Name值。 There can be duplicates in this collection so I want only the unique ones. 此收藏中可以有重复的商品,因此我只需要唯一的商品。

It seems like this should do the trick but it does not, it returns all the items regardless of dupes. 看起来这应该可以解决问题,但事实并非如此,它会返回所有项目,而不管是否有重复。 What am I doing wrong here? 我在这做错了什么?

List<MyClass> items = (from MyClass mc in collectionOfProps 
select new MyClass() { 
Id = collectionOfProps.Properties[0], 
Name = collectionOfProps.Properties[1] }).Distinct().ToList();

The problem is likely that MyClass does not implement IEquatable<MyClass> as well as override Equals and GetHashCode . 问题可能是MyClass不实现IEquatable<MyClass>以及重写EqualsGetHashCode

In order to make Distinct() work the way you want, you have to implement IEquatable<T> . 为了使Distinct()以您想要的方式工作,必须实现IEquatable<T> Otherwise, it uses the default (reference equality) for checking, which means it would only determine the elements were not distinct if they were the same exact instance. 否则,它将使用默认值(引用相等)进行检查,这意味着,如果元素是相同的确切实例,则它将仅确定元素是否不同。

您需要重写Equals() GetHashCode()才能按值比较实例。

Have you overridden equality (for distinct) in MyClass? 您是否在MyClass中覆盖了相等性(对于不同的而言)? My guess would be no. 我的猜测不会。

According to the docs: 根据文件:

http://msdn.microsoft.com/en-us/library/bb348436.aspx http://msdn.microsoft.com/en-us/library/bb348436.aspx

The default equality comparer, Default, is used to compare values of the types that implement the IEquatable(Of T) generic interface. 默认的相等比较器Default用于比较实现IEquatable(T)通用接口的类型的值。 To compare a custom data type, you need to implement this interface and provide your own GetHashCode and Equals methods for the type. 要比较自定义数据类型,您需要实现此接口并为该类型提供自己的GetHashCode和Equals方法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM