为什么 GroupBy 多个字段没有正确分组>
Why is GroupBy multiple fields not grouping correctly>
我有一个带有时间戳的模型对象 属性,我想按年和月对它们进行分组,所以我这样做了:
'group the events by months
Dim months = Model.Events.GroupBy(Function(x) New With {x.Timestamp.Year, x.Timestamp.Month})
但这实际上是为每个事件返回一个组,即使是那些具有相同年份和月份的事件:
这是怎么回事?为什么 GroupBy
为每个事件创建一个单独的组,而不是按年和月分组,我该如何解决这个问题?
只有不可变的 Key
属性才能确定相等性。如果没有关键属性,您将获得引用相等性。
New With {Key x.Timestamp.Year, Key x.Timestamp.Month}
Key Properties
Key properties differ from non-key properties in several fundamental ways:
Only the values of key properties are compared in order to determine whether two instances are equal.
The values of key properties are read-only and cannot be changed.
Only key property values are included in the compiler-generated hash code algorithm for an anonymous type.
Equality
Instances of anonymous types can be equal only if they are instances of the same anonymous type. The compiler treats two instances as instances of the same type if they meet the following conditions:
They are declared in the same assembly.
Their properties have the same names, the same inferred types, and are declared in the same order. Name comparisons are not case-sensitive.
The same properties in each are marked as key properties.
At least one property in each declaration is a key property.
An instance of an anonymous types that has no key properties is equal only to itself.
我有一个带有时间戳的模型对象 属性,我想按年和月对它们进行分组,所以我这样做了:
'group the events by months
Dim months = Model.Events.GroupBy(Function(x) New With {x.Timestamp.Year, x.Timestamp.Month})
但这实际上是为每个事件返回一个组,即使是那些具有相同年份和月份的事件:
这是怎么回事?为什么 GroupBy
为每个事件创建一个单独的组,而不是按年和月分组,我该如何解决这个问题?
只有不可变的 Key
属性才能确定相等性。如果没有关键属性,您将获得引用相等性。
New With {Key x.Timestamp.Year, Key x.Timestamp.Month}
Key Properties
Key properties differ from non-key properties in several fundamental ways:
Only the values of key properties are compared in order to determine whether two instances are equal.
The values of key properties are read-only and cannot be changed.
Only key property values are included in the compiler-generated hash code algorithm for an anonymous type.
Equality
Instances of anonymous types can be equal only if they are instances of the same anonymous type. The compiler treats two instances as instances of the same type if they meet the following conditions:
They are declared in the same assembly.
Their properties have the same names, the same inferred types, and are declared in the same order. Name comparisons are not case-sensitive.
The same properties in each are marked as key properties.
At least one property in each declaration is a key property.
An instance of an anonymous types that has no key properties is equal only to itself.