0

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")
          )
ekad
  • 14,436
  • 26
  • 44
  • 46
user2455595
  • 67
  • 1
  • 2
  • 9

1 Answers1

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"))
          })
MarcinJuraszek
  • 124,003
  • 15
  • 196
  • 263
  • When i use the code, i get the following error: the focus is on the word Group in the line: Group e By Key = New With – user2455595 Feb 02 '14 at 17:58
  • from another post i found the reason is missing – user2455595 Feb 02 '14 at 18:19
  • the problem is that the group isn't performed. the outcome contain 2 lines with same ProductName and GroupName (and different QTY). the lines should have been combined and the sum should be combined as well. why the group isn't performed? – user2455595 Feb 03 '14 at 11:06
  • i was trying to add the code which isn't working but unable to do it. i opened seperate issue because i can't insert code inside comment and it's not an answer. please see http://stackoverflow.com/questions/21527993/how-to-perform-correctly-groupby-in-linq-on-datatable-inside-vb-code – user2455595 Feb 03 '14 at 12:55
  • @MarcinJuraszek, I've a similar problem with dynamical grouping using LINQ. Can you please have a look [here](http://stackoverflow.com/questions/22694680/how-to-use-linq-for-conditional-grouping-and-filtering-on-a-datatable)? – Cheshire Cat Apr 01 '14 at 10:50