这code返回不同的值。不过,我要的是返回一个强类型集合,而不是匿名类型 [英] This code returns distinct values. However, what I want is to return a strongly typed collection as opposed to an anonymous type

查看:147
本文介绍了这code返回不同的值。不过,我要的是返回一个强类型集合,而不是匿名类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下的code:

var foo = (from data in pivotedData.AsEnumerable()
                   select new
                   {
                     Group = data.Field<string>("Group_Number"),
                     Study = data.Field<string>("Study_Name")
                   }).Distinct();

由于预计今年将返回不同的值。不过,我想是返回一个强类型集合,而不是匿名类型,所以当我做的:

As expected this returns distinct values. However, what I want is to return a strongly-typed collection as opposed to an anonymous type, so when I do:

var foo = (from data in pivotedData.AsEnumerable()
                   select new BarObject
                   {
                     Group = data.Field<string>("Group_Number"),
                     Study = data.Field<string>("Study_Name")
                   }).Distinct();

这不返回不同的值,则返回了他们。有没有一种方法与实际对象做到这一点?

This does not return the distinct values, it returns them all. Is there a way to do this with actual objects?

推荐答案

有关鲜明的()(和许多其他LINQ功能)工作,类被比较( BarObject 在你的例子)必须实现实施等于() GetHash code() ,或者提供一个单独的的IEqualityComparer&LT; T&GT; 作为参数传递给鲜明的()

For Distinct() (and many other LINQ features) to work, the class being compared (BarObject in your example) must implement implement Equals() and GetHashCode(), or alternatively provide a separate IEqualityComparer<T> as an argument to Distinct().

许多LINQ方法利用 GetHash code()的性能,因为在内部,他们会使用的东西,像设置&LT的; T&GT; 持有独特的项目,它采用了O(1)查找散列。此外, GetHash code()可以很快告诉你,如果两个对象的可能的是等价的,哪些是绝对不会 - 只要 GetHash code()正确实施,当然。

Many LINQ methods take advantage of GetHashCode() for performance because internally they will use things like a Set<T> to hold the unique items, which uses hashing for O(1) lookups. Also, GetHashCode() can quickly tell you if two objects may be equivalent and which ones are definitely not - as long as GetHashCode() is properly implemented of course.

所以,你应该让所有的课程你打算在LINQ比较实施等于() GetHash code()的完整性,或创建一个单独的的IEqualityComparer&LT; T&GT; 实施

So you should make all your classes you intend to compare in LINQ implement Equals() and GetHashCode() for completeness, or create a separate IEqualityComparer<T> implementation.

这篇关于这code返回不同的值。不过,我要的是返回一个强类型集合,而不是匿名类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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