How to perform correctly "group by" in linq on DataTable inside vb code?

linq, vb.net

Solution

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.

Problem

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

Original source