LINQ SELECT DISTINCT与匿名类型 [英] LINQ Select Distinct with Anonymous Types

查看:478
本文介绍了LINQ SELECT DISTINCT与匿名类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我有对象的集合。的确切类型并不重要。从中我想提取一对特定属性的所有唯一对,正是如此:

So I have a collection of objects. The exact type isn't important. From it I want to extract all the unique pairs of a pair of particular properties, thusly:

myObjectCollection.Select(item=>new
                                {
                                     Alpha = item.propOne,
                                     Bravo = item.propTwo
                                }
                 ).Distinct();

所以我的问题是:分明在这种情况下使用默认的对象等于(这将是对我没用,因为每个对象是新的),或者可以在被告知做了不同的equals(在这种情况下,有相等的值阿尔法和Bravo =>等于实例)?有没有什么办法来实现这一结果,如果不这样做呢?

So my question is: Will Distinct in this case use the default object equals (which will be useless to me, since each object is new) or can it be told to do a different equals (in this case, equal values of Alpha and Bravo => equal instances)? Is there any way to achieve that result, if this doesn't do it?

推荐答案

有一个通过K.斯科特·艾伦的出色的帖子在这里阅读:

Have a read through K. Scott Allen's excellent post here:

平等,人人...匿名类型

简短的回答(我引用):

The short answer (and I quote):

原来C#编译器覆盖
  equals和GetHash code匿名
  类型。两个实施
  覆盖方法使用所有市民
  上的类型的属性来计算
  对象的哈希code和测试
  平等。如果相同的两个对象
  匿名类型都相同
  他们的属性的值 - 该
  对象是相等的。

Turns out the C# compiler overrides Equals and GetHashCode for anonymous types. The implementation of the two overridden methods uses all the public properties on the type to compute an object's hash code and test for equality. If two objects of the same anonymous type have all the same values for their properties – the objects are equal.

所以这是完全可以放心使用DISTINCT()方法返回匿名类型的查询。

So it's totally safe to use the Distinct() method on a query that returns anonymous types.

这篇关于LINQ SELECT DISTINCT与匿名类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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