Reputation: 59
I have 2 datatable
TABLE1
Type Count
Orange 2
Apple 3
Pear 6
TABLE2
Type Count
Orange 3
Pear 2
Pineapple 1
Banana 4
I want to combine table 1 and table 2 and add both count. TABLE 3 as example
TABLE3
Type Count
Orange 5
Apple 3
Pear 8
Pineapple 1
Banana 4
Upvotes: 0
Views: 372
Reputation: 460208
You can use Linq-To-DataTable
to group by type and sum the count:
var typeGroups = Table1.AsEnumerable()
.Concat(Table2.AsEnumerable()) // all rows in one sequence
.GroupBy(row => row.Field<string>("Type")); // group all by type
DataTable Table3 = Table1.Clone(); // empty, same columns
foreach (var typeGroup in typeGroups)
{
DataRow newRow = Table3.Rows.Add(); // added already now
newRow.SetField("Type", typeGroup.Key);
newRow.SetField("Count", typeGroup.Sum(row => row.Field<int>("Count")));
}
Upvotes: 1