I am trying to group 7 objects (of Type ABPM) by date and hour and not getting correct results.
Private Class ABPM
Public DT As Date = Date.Now
Public Hour As Integer = 0
Public Minute As Integer = 0
Public SBP As Integer = 0
Public DBP As Integer = 0
End Class
Dim abpms As New List(Of ABPM)
The following query produces 7 groups instead of 2
Dim hourlyDayGroup2 = abpms.GroupBy(Function(a As ABPM) New With {a.DT, a.Hour})
But this one (without lambda) outputs only 2 group which is correct
Dim hourlyDayGroup = From a As ABPM In abpms _
Group By a.DT, a.Hour Into Group
What is the correct way to write the lambda query? Thanks
You need to make your anonymous type use Key
properties, so that they participate in equality computations:
Dim hourlyDayGroup2 = abpms.GroupBy(Function(a As ABPM) New With {Key a.DT, Key a.Hour})
From MSDN:
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.
Note that in C#, all properties of anonymous types have the same semantics as key properties in VB.
See more on this question at Stackoverflow