如何在 vb 代码内在 linq 中正确执行 "group by" 数据表?



为什么以下组不使用以下组?最初的问题是如何在linq内部的linq内部(dot.net v4.0)中使用DataPable和组上进行组?这是样本,但没有产生所需的输出。它返回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
                     })

在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
                 })

使用您的语法,它仅使用匿名对象上的默认平等比较,该对象不会比较字段。

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

最新更新