user1626874 user1626874 - 1 month ago 16
Vb.net Question

Multi property lambda groupby does not return correct result

Trying to group a list of records with lambda but does not work with multiple property

I hate stake over flow, here is a bunch of text that is not need because stack over flow say I need more text because there is too much code and there stupid validation system keeps say my code is incorrectly formatted and I have spent to much time trying to get this to post

Module Module1
Sub Main()
Dim list As New List(Of MyObject)
list.Add(New MyObject() With {.Batch = "", .Expiry = New Date(2001, 1, 1), .Serial = "S1"})
list.Add(New MyObject() With {.Batch = "", .Expiry = New Date(2001, 1, 1), .Serial = "S5"})
list.Add(New MyObject() With {.Batch = "", .Expiry = New Date(2001, 1, 2), .Serial = "S2"})
list.Add(New MyObject() With {.Batch = "", .Expiry = New Date(2001, 1, 3), .Serial = "S3"})
list.Add(New MyObject() With {.Batch = "", .Expiry = New Date(2001, 1, 4), .Serial = "S4"})

Dim distinct As List(Of MyObject) = list.GroupBy(Function(x) New With {Key .Batch = x.Batch.ToUpper().Trim(), .Expiry = x.Expiry.Date}, Function(x) x).Select(Function(x) New MyObject() With {.Batch = x.Key.Batch, .Expiry = x.Key.Expiry, .Serial = ""}).ToList()
End Sub

Public Class MyObject
Property Batch As String
Property Expiry As Date
Property Serial As String
End Class
End Module


'Expected Results:
'item 0: Batch = "", Expiry = 2001/1/01, Serial = ""
'item 1: Batch = "", Expiry = 2001/1/02, Serial = ""
'item 2: Batch = "", Expiry = 2001/1/03, Serial = ""
'item 3: Batch = "", Expiry = 2001/1/04, Serial = ""

'Actual Results:
'item 0: Batch = "", Expiry = 2001/1/01, Serial = ""

Answer

You have miss a keyword Key in your group by

Your code:

list.GroupBy(Function(x) New With {Key .Batch = x.Batch.ToUpper().Trim(), .Expiry = x.Expiry.Date}, Function(x) x)

But it should be

list.GroupBy(Function(x) New With {Key .Batch = x.Batch.ToUpper().Trim(), Key .Expiry = x.Expiry.Date}, Function(x) x)

Fiddler