LINQ Group按匿名类型

标签 linq group-by anonymous-types

我想知道为什么 GroupBy 与匿名类型一起使用。

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

匿名类型不实现任何接口(interface),所以我很困惑这是如何工作的。

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

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

最佳答案

根据文档,anonymous type is a reference type :

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



因此,它将使用 System.Object 实现的那些功能的默认实现。 (至少对于 equality is based on referential equality )。

编辑 :实际上,根据相同的第一个 doco 链接,它说:

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按匿名类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9793416/

相关文章:

c# - C#中单个&符号的第二个含义是什么?

mysql - 对列中的值进行 Group by 子句

mysql - SQL分组组合?

mysql - SQL - 按问题分组

c# - Linq orderby 没有按预期工作

c# - LINQ on 循环条件

c# - 在 C# 中使用 {...} 和 new 实例化匿名类型

c# - Entity Framework 6.1.3 : Projection - load children of children directly

.net - 匿名类型的目的是什么?

c# - 将匿名类型的对象作为参数传递给方法