LINQ Group通过匿名类型 [英] LINQ GroupBy Anonymous Type

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

问题描述

我想知道为什么GroupBy使用匿名类型.

I am wondering why GroupBy works with anonymous types.

List<string> values = new List<string>();
values.GroupBy(s => new { Length = s.Length, Value = s })

匿名类型没有实现任何接口,所以我感到困惑.

Anonymous types do not implement any interfaces, so I am confused how this is working.

我假设算法是通过为源中的每个项目创建一个匿名类型的实例并使用散列将这些项目组合在一起而起作用的.但是,没有提供IEqualityComparer来定义如何生成哈希或两个实例是否相等.那么,我认为Object.Equals和Object.GetHashCode方法将是依赖对象标识的后备.

I assume that the algorithm is working by creating an instance of the anonymous type for each item in the source and using hashing to group the items together. However, no IEqualityComparer is provided to define how to generate a hash or whether two instances are equal. I would assume, then, that the Object.Equals and Object.GetHashCode methods would be the fallback, which rely on object identity.

那么,这如何按预期工作?但是,它在OrderBy中不起作用.匿名类型会覆盖Equals和GetHashCode吗?还是底层的GroupBy算法会做一些我没想到的魔术?

So, how is it that this is working as expected? And yet it doesn't work in an OrderBy. Do anonymous types override Equals and GetHashCode? or does the underlying GroupBy algorithm do some magic I haven't thought of?

推荐答案

根据文档,匿名类型是引用类型:

从公共语言运行时的角度来看,匿名类型与任何其他引用类型没有什么不同.

From the perspective of the common language runtime, an anonymous type is no different from any other reference type.

因此,它将使用由相等性基于引用平等).

Therefore, it will be using the default implementation for those functions as implemented by System.Object (which at least for equality is based on referential equality).

编辑:实际上,按照它说的第一个doco链接:

EDIT: Actually, as per that same first doco link it says:

由于匿名类型的Equals和GetHashCode方法是根据属性的Equals和GetHashcode方法定义的,因此只有所有匿名属性都相等时,相同匿名类型的两个实例才相等.

Because the Equals and GetHashCode methods on anonymous types are defined in terms of the Equals and GetHashcode methods of the properties, two instances of the same anonymous type are equal only if all their properties are equal.

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

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