Search code examples
vb.netlinqlinq-group

how to perform groupby in linq on DataTable inside vb code?


How do I perform group in LINQ inside vb code (dot.net v4.0) with DataTable and sum on the group?

In the sample below I need to add group by GroupName, ProductName and perform sum on QTY. The columns, order and where should remain as in sample, I just need to add the group and sum. The format should remain the same (getting row using 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")
          )

Solution

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