如何在vb代码中的DataTable上执行linq中的groupby?

时间:2014-02-02 17:27:04

标签: vb.net linq linq-group

如何使用DataTable在vb代码(dot.net v4.0)中的LINQ中执行组并对组进行求和?

在下面的示例中,我需要按GroupNameProductName添加分组,并在QTY上执行总和。列,顺序和位置应保留为样本,我只需要添加组和总和。格式应保持不变(使用e(“FieldName”)获取行。)

Dim ordersTable As DataTable = _dsProd.Tables("tblProductSummary")
Dim query =
         (From e In ordersTable
          Where (e("Type").ToString() = "1" Or IsDBNull(e("Type")))
          Order By e("GroupSortOrder") Ascending, e("ProductName")
          Select
            GroupName = e("GroupName"),
            ProductName = e("ProductName"),
            QTY = e("QTY"),
            Type= e("Type")
          )

1 个答案:

答案 0 :(得分:0)

Dim query =
         (From e In ordersTable
          Where (e("Type").ToString() = "1" Or IsDBNull(e("Type")))
          Order By e("GroupSortOrder") Ascending, e("ProductName")
          Group e By Key = New With {
              .ProductName = e("ProductName"),
              .GroupName = e("GroupName")
          } Into Group
          Select New With {
              .ProductName = Key.ProductName,
              .GroupName = Key.GroupName,
              .Sum = Group.Sum(Function(x) x("QTY"))
          })