问题描述
假设我有一个称为myClass的类,该类别具有两个属性(int ID和一个字符串名称).我想从另一个集合中填充这些myllass对象的列表,但我只想要独特的对象.另一个集合是一个第三方对象,具有名为"属性"的属性,该对象只是一个值数组,其中的前两个对应于我关心的ID和名称值.该系列中可以有重复的内容,因此我只想要独特的内容.
看来这应该可以解决问题,但它却没有,它返回所有项目,无论欺骗什么.我在这里做错了什么?
List<MyClass> items = (from MyClass mc in collectionOfProps select new MyClass() { Id = collectionOfProps.Properties[0], Name = collectionOfProps.Properties[1] }).Distinct().ToList();
推荐答案
问题可能是MyClass不实现 IEquatable<MyClass> 以及覆盖Equals和GetHashCode.
为了按照您想要的方式进行Distinct(),您必须实现 IEquatable<T>
其他推荐答案
您需要覆盖Equals() 和GetHashCode() 才能按值比较实例.
其他推荐答案
您是否在myclass中覆盖了平等(不同)?我的猜测是没有.
根据文档:
默认平等比较(默认值)用于比较实现Iquable(t)通用接口的类型的值.要比较自定义数据类型,您需要实现此界面并提供自己的GethashCode并等于该类型的方法.
问题描述
Assume I have a class called MyClass that has two properties (int Id and a string Name). I want to populate a List of these MyClass objects from another collection but I want only the unique ones. 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. 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.
In order to make Distinct() work the way you want, you have to implement 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.
其他推荐答案
You need to override Equals() and GetHashCode() to compare instances by value.
其他推荐答案
Have you overridden equality (for distinct) in MyClass? My guess would be no.
According to the docs:
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. To compare a custom data type, you need to implement this interface and provide your own GetHashCode and Equals methods for the type.