Reputation: 13848
I've got a model object with a Timestamp property, and I want to group these by year and month, so I did this:
'group the events by months
Dim months = Model.Events.GroupBy(Function(x) New With {x.Timestamp.Year, x.Timestamp.Month})
But this is actually returning a group for every event, even ones with the same year and month:
What's going on here? Why is GroupBy
making a separate group for every event, instead of grouping by year and month, and how can I fix this?
Upvotes: 2
Views: 571
Reputation: 108830
Only immutable Key
properties determine equality. If there are no key properties, you get reference equality.
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.
Upvotes: 3