I have a DataTable with multiple columns. If the value of certain column repeats, I need to remove that row and add the quantities against it. For example, following datatable
ITEM QTY
------------
1 20
2 10
2 10
3 20
would become:
ITEM QTY
-----------
1 20
2 20
3 20
This is what I did
var table = dt.AsEnumerable()
.GroupBy(row => row.Field("ITEM"))
.Select(group => group.First())
.CopyToDataTable();
It removes the extra row but doesn't add up the quantities. So please help me in this regard.
You can use
Sum
. You just have to find the duplicate-rows first:Now you can use them to get the sum and to remove the redundant rows from the table.
Or in one query which creates a new
DataTable
.However, even the second approach modifies the original table which might be undesired since you use
CopyToDatatable
to create a newDataTable
. You need to clone the original table(DataTable newTable = dt.Clone();
) to get an empty table with the same schema. Then useNewRow
+ItemArray.Clone()
ortable.ImportRow
to create a real clone without modifying the original data.See: C# simple way to copy or clone a DataRow?
Edit: Here is an example how you can create a clone without touching the original table: