Search code examples
vb.netlinqlinq-method-syntax

Vb.net LINQ Syntax Group By Multiple Columns using Method Syntax


I have a LINQ expression that looks something like this

    Dim DataRowDueTo = From row In DataTableDueTo.AsEnumerable
                       Where row.Field(Of UInt32)("Transaction") = 1 And {"A", "B", "C"}.Contains(row.Field(Of String)("Module"))
                       Group By x = New With {Key .CustID = row.Field(Of UInt32)("CustID"), Key .Module = row.Field(Of String)("Module")} Into g = Group
                       Select New With {
                       .CustID = x.CustID,
                       .Module = x.Module,
                       .Sum= g.Sum(Function(r) r.Field(Of Decimal)("Amount"))
                       }

    ''DataTableDueToFinal is a datatable i have precreated with columns (CustID,Module and Sum)
    For Each grp In DataRowDueTo
        DataTableDueToFinal.Rows.Add(grp.CustID, grp.Module, grp.Sum)
    Next

Essentially, I have a set of data (from a DataTable) which I GROUP BY 2 columns(CustID and Module) filtered using Where by TransactionSource and Module.

The results Produced would look something like this

+--------+--------+-----+
| CustID | Module | Sum |
+--------+--------+-----+
| 1      | A      | 50  |
+--------+--------+-----+
| 1      | B      | 45  |
+--------+--------+-----+
| 2      | A      | 23  |
+--------+--------+-----+
| 3      | A      | 234 |
+--------+--------+-----+
| 3      | B      | 76  |
+--------+--------+-----+

My Problem is, I am trying to reproduce the same results using a different approach but I can't get the desired results.

    Dim DataRowDueTo = DataTableDueTo.AsEnumerable().Where(Function(w) w.Field(Of UInt32)("Transaction") = 1 And {"A", "B", "C"}.Contains(w.Field(Of String)("Module"))) _
                                                          .GroupBy(Function(row) {row.Field(Of UInt32)("CustID"), row.Field(Of String)("Module")})
          ''DataTableDueToFinal is a datatable i have precreated with columns (CustID,Module and Sum)
    For Each grp In DataRowDueTo
        DataTableDueToFinal.Rows.Add(grp.Key(0), grp.Key(1), grp.Sum(Function(row) row.Field(Of Decimal)("Amount")))
    Next

Can anyone point out where have I gone wrong? Thank you for your time and consideration.


Solution

  • Looks like this might work:

    Dim DataRowDueTo = DataTableDueTo.AsEnumerable().Where(Function(w) w.Field(Of UInt32)("Transaction") = 1 And {"A", "B", "C"}.Contains(w.Field(Of String)("Module"))) _
                                                          .GroupBy(Function(row) New With {KEY .CustID = row.Field(Of UInt32)("CustID"),Key .Module = row.Field(Of String)("Module")})
          ''DataTableDueToFinal is a datatable i have precreated with columns (CustID,Module and Sum)
    For Each grp In DataRowDueTo
        DataTableDueToFinal.Rows.Add(grp.Key.CustID, grp.Key.Module, grp.Sum(Function(row) row.Field(Of Decimal)("Amount")))
    Next