Reputation: 892
I want to Group By on a List using VB.Net. Seems simple but I can't make it work. I've tried:
Dim groupedEmails = saEmails.GroupBy(Function(m) New With {m.Property1, m.Property2, m.Property3.SubProperty1})
I have 6 items in saEmails and two of the items have the same Property1, Property2 and Property3. Unfortunately, at runtime I'm still getting 6 items in groupedEmails even though my grouping should reduce that count to 5.
I've tried the statement without the "New With" (it still compiles) but the result is the same. I also can't get Linq to Entities ("From mail in saEmails...") to accept my use of the keyword "Group". I have Imported System.Linq.
I would also be happy with a working use of .ToLookup().
The entities are similar to this:
Namespace Something
<DataContract()>
Public Class SAEmail
<DataMember()>
Public Property Property1 As Integer
<DataMember()>
Public Property Property2 As String
<DataMember()>
Public Property Property3 As Blah
<DataMember()>
Public Property Property4 As String
Public Overrides Function Equals(obj As Object) As Boolean
If obj Is Nothing OrElse Not Me.GetType() Is obj.GetType() Then
Return False
End If
Dim email As SAEmail = CType(obj, SAEmail)
Return Property1 = email.Property1 _
AndAlso Property2 = email.Property2 _
AndAlso Property1.SubProperty1 = email.Property3.SubProperty1
End Function
Public Overrides Function GetHashCode() As Integer
Return CInt(CLng(Property1) Xor CLng(Property2) Xor CLng(Property3.SubProperty1))
End Function
End Class
<DataContract()>
Public Class Blah
<DataMember()>
Public Property SubProperty1 As Integer
<DataMember()>
Public Property SubProperty2 As String
End Class
End Namespace
Ideas?
Upvotes: 0
Views: 664
Reputation: 754
How about creating a composite grouping key?
Dim groupedEmails = saEmails.GroupBy(Function(m) String.Format("{0}:{1}:{2}", m.Property1, m.Property2, m.Property3.SubProperty1))
Or, using an interpolated string when VB14 is released in a few weeks!:
Dim groupedEmails = saEmails.GroupBy(Function(m) $"{m.Property1}:{m.Property2}:{m.Property3.SubProperty1)}")
Upvotes: 1