如何在vb代码内的DataTable上的linq中正确执行“group by”?

2023-12-15

为什么以下 group by 子句不起作用? 最初的问题是如何在 LINQ 内的 vb 代码 (dot.net v4.0) 中使用 DataTable 和组上的总和执行组?这是示例,但它没有产生所需的输出。 它返回 2 行而不是 1 行。

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

使用您的语法,它仅在匿名对象上使用默认的相等比较器,而不比较字段。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如何在vb代码内的DataTable上的linq中正确执行“group by”? 的相关文章

随机推荐