c#数据表合并和添加值

本文关键字:添加 合并 数据表 | 更新日期: 2023-09-27 18:08:01

我有两个数据表

TABLE1

 Type        Count
Orange         2
Apple          3
Pear           6

 Type        Count
Orange         3
Pear           2
Pineapple      1
Banana         4

我想合并表1和表2两个数相加。表3为例

TABLE3

  Type        Count
    Orange         5
    Apple          3
    Pear           8
    Pineapple      1
    Banana         4

c#数据表合并和添加值

您可以使用Linq-To-DataTable按类型分组并求和计数:

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")));
}