为什么此LINQ查询不按预期工作?[英] Why doesn't this LINQ query work as expected?

本文是小编为大家收集整理的关于为什么此LINQ查询不按预期工作?的处理/解决方法,可以参考本文帮助大家快速定位并解决问题,中文翻译不准确的可切换到English标签页查看源文。

问题描述

假设我有一个称为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中覆盖了平等(不同)?我的猜测是没有.

根据文档:

BB348436.aspx

默认平等比较(默认值)用于比较实现Iquable(t)通用接口的类型的值.要比较自定义数据类型,您需要实现此界面并提供自己的GethashCode并等于该类型的方法.

本文地址:https://www.itbaoku.cn/post/1556787.html

问题描述

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.