如何在vb代码中的DataTable上正确执行linq中的"分组依据"?

use*_*595 2 linq vb.net

为什么以下group by子句不起作用?最初的问题是我如何在带有DataTable的vb代码(dot.net v4.0)中的LINQ中执行组并对组进行求和?这是样本,但它没有产生所需的输出.它返回2行而不是一行.

    Dim table As New DataTable()
    table.Columns.Add("GroupName", GetType(String))
    table.Columns.Add("ProductName", GetType(String))
    table.Columns.Add("QTY", GetType(Integer))

    table.Rows.Add("a", "b", 1)
    table.Rows.Add("a", "b", 1)


    Dim testQuery =
                     (From e In table
                      Group e By Key = New With {
                        .GroupName = e("GroupName"),
                        .ProductName = e("ProductName")
                      } Into Group
                      Select New With {
                        .ProductName = Key.ProductName,
                        .QTY = Group.Sum(Function(x) Convert.ToInt32(x("QTY"))),
                        .GroupName = Key.GroupName
                     })
Run Code Online (Sandbox Code Playgroud)

nmc*_*ean 6

在VB.NET中,按组合键分组的语法是逗号分隔键,而不是匿名类型:

                 (From e In table
                  Group e By
                    GroupName = e("GroupName"),
                    ProductName = e("ProductName")
                  Into Group
                  Select New With {
                    .ProductName = ProductName,
                    .QTY = Group.Sum(Function(x) Convert.ToInt32(x("QTY"))),
                    .GroupName = GroupName
                 })
Run Code Online (Sandbox Code Playgroud)

使用您的语法,它只使用匿名对象上的默认相等比较器,它不会比较字段.