多属性lambda groupby不会返回正确的结果

时间:2016-10-26 04:44:14

标签: vb.net lambda group-by

尝试使用lambda对记录列表进行分组,但不能使用多个属性

我讨厌对流量的利益,这里有一堆不需要的文本,因为堆栈溢出说我需要更多文本,因为代码太多而且有愚蠢的验证系统一直说我的代码格式不正确而且我花了很多时候试图发布

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 = ""

1 个答案:

答案 0 :(得分:1)

您的小组中错过了关键字Key

您的代码:

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

但它应该是

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

Fiddler