My requirement is merging of rows where ID's are same with same values in each columns and summing up its Amount and Percentage columns.
Datatable example as given bellow -
Datatable (dtrec)
COL1 COL2 COL3 ID AMT PERCENTAGE COL4
-----------------------------------------------------
2022 2024 2021 5001 400 .20 213
2022 2024 2021 5001 400 .20
2031 2021 2134 6001 500 .20
Expected Result -
Desired Output - Datatable (dtrec)
COL1 COL2 COL3 ID AMT PERCENTAGE COL4
-----------------------------------------------------
2022 2024 2021 5001 800 .40 213
2031 2021 2134 6001 500 .20
By using bellow linq statement i am receiving an output like bellow -
DataTable dt = dtrec.AsEnumerable()
.GroupBy(r => r.Field<decimal>("ID"))
.Select(g =>
{
var row = dtrec.NewRow();
row["ID"] = g.Key;
row["AMT"] = g.Sum(r => r.Field<decimal>("AMT"));
row["PERCENTAGE"] = g.Sum(r => r.Field<decimal>("PERCENTAGE"));
return row;
}).CopyToDataTable();
Datatable (dt)
COL1 COL2 COL3 ID AMT PERCENTAGE COL4
-----------------------------------------------------
5001 800 .40
6001 500 .20
As mentioned above my requirement is that, a linq statement, that would select all columns from datatable and additionally it would be summing up AMT and PERCENTAGE columns. As shown in desired result.
Another important point to consider that apart from ID, AMT and PERCENTAGE columns other columns are dynamic i.e. columns might increase or decrease (e.g. COL1, COL2, COL3, COL4, COl5.... etc) hence we cannot include COL1 or COL4 inside select statement.
Any suggestion would be helpful.
Thanks
COL1orCOL4they won't be in the result. - Sach