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

查看:51
本文介绍了为什么此LINQ查询无法按预期工作?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有一个名为MyClass的类,该类具有两个属性(int Id和一个字符串Name).我想从另一个集合中填充这些MyClass对象的列表,但我只想要唯一的对象.这个另一个集合是一个第三方对象,该对象具有名为"Properties"的属性,该属性只是一个值数组,其中前两个对应于我关心的Id和Name值.此收藏夹中可以有重复项,因此我只需要唯一的重复项.

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();

推荐答案

问题很可能是MyClass未实现

The problem is likely that MyClass does not implement IEquatable<MyClass> as well as override Equals and GetHashCode.

为了使Distinct()以您想要的方式工作,您必须实现 IEquatable<T> .否则,它将使用默认值(引用相等)进行检查,这意味着,如果它们是相同的确切实例,则只会确定元素没有区别.

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.

这篇关于为什么此LINQ查询无法按预期工作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆