I need to group rows in a DataTable by a specific column, calculate the sum of another column for each group, and show only one representative row for each group along with the calculated sum.
Here is the LINQ query I’m currently using:
From row In dtDepGrouped.AsEnumerable()
Group row By key = row("GroupColumn").ToString() Into grp = Group
Let sumValueColumn = grp.Sum(Function(r) Convert.ToDouble(r("ValueColumn")))
Let firstRow = grp.First()
Select dtDepGrouped.Rows.Add({
firstRow ("IDColumn").ToString(),
firstRow ("CategoryColumn").ToString(),
firstRow ("DateColumn").ToString(),
firstRow ("AmountColumn").ToString(),
firstRow ("BalanceColumn").ToString(),
firstRow ("AccountColumn").ToString(),
sumValueColumn,
firstRow ("AssignedColumn").ToString(),
firstRow("GroupColumn").ToString(),
firstRow ("OrderNumberColumn").ToString(),
firstRow ("DescriptionColumn").ToString(),
firstRow ("SupplierColumn").ToString(),
firstRow ("InvoiceColumn").ToString(),
groupedRow("SegmentColumn").ToString()
})
).CopyToDataTable()
In the above query:
GroupColumn is the column by which I want to group the rows.
ValueColumn is the column for which I want to calculate the sum for each group.
The rest of the columns (IDColumn, CategoryColumn, DateColumn, etc.) are additional columns that I need to include in the output DataTable.
My goal is to group the rows by GroupColumn, calculate the sum of ValueColumn for each group, and show only one representative row for each group along with the sum of ValueColumn for the entire group.
However, the above query is currently adding all rows from each group to the resulting DataTable and shown to me only the first row for ‘ValueColumn’ also and I need all the SUM of whole rows for each group, which is not the output from my query. Could someone help me correct this query so that it achieves my goal?
Dim groupedRows = From row In dtDepGrouped.AsEnumerable()
Group row By key = row("GroupColumn").ToString() Into grp = Group
Let sumValueColumn = grp.Sum(Function(r) Convert.ToDouble(r("ValueColumn")))
Let firstRow = grp.First()
Select dtDepGrouped.Rows.Add({
firstRow("IDColumn").ToString(),
firstRow("CategoryColumn").ToString(),
firstRow("DateColumn").ToString(),
firstRow("AmountColumn").ToString(),
firstRow("BalanceColumn").ToString(),
firstRow("AccountColumn").ToString(),
sumValueColumn,
firstRow("AssignedColumn").ToString(),
firstRow("GroupColumn").ToString(),
firstRow("OrderNumberColumn").ToString(),
firstRow("DescriptionColumn").ToString(),
firstRow("SupplierColumn").ToString(),
firstRow("InvoiceColumn").ToString(),
firstRow("SegmentColumn").ToString()
})
resultDataTable = dtDepGrouped.Clone()
For Each row As DataRow In groupedRows
resultDataTable.ImportRow(row)
Next
Put this code inside the Invoke code pass the arguments resultDataTable as Out
dtDepGrouped as in argument
Try this in assign…first use a build datatable and create the table you need with required columns and call it newdt and data lets assume is present in dt