如何正确执行“分组依据"?在LINQ上的VB代码里面的DataTable? [英] How to perform correctly "group by" in linq on DataTable inside vb code?

查看:75
本文介绍了如何正确执行“分组依据"?在LINQ上的VB代码里面的DataTable?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

Why isn't the following group by clause working? The original question was how do I perform group in LINQ inside vb code (dot.net v4.0) with DataTable and sum on the group? This was the sample, but it's not producing the desired output. It returns 2 lines instead of one line.

    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中,按组合键分组的语法是逗号分隔的键,而不是匿名类型:

In VB.NET, the syntax for grouping by composite keys is comma-separated keys, not an anonymous type:

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

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

With your syntax, it just uses the default equality comparer on the anonymous objects, which doesn't compare the fields.

这篇关于如何正确执行“分组依据"?在LINQ上的VB代码里面的DataTable?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆