所以基于目前的现有动作,合并表格变量是不是没有办法做的?
表格变量,底层为DataTable类型,可以参考如下Ai提供的信息,在表达式里合并数据试一下。问题: c# 两个DataTable如何合并,或者说,如将一个里的内容,合并到另一个里?
C# 里两个 DataTable 合并,最常用的是 DataTable.Merge()。
DataTable
DataTable.Merge()
DataTable table1 = ...; DataTable table2 = ...; // 将 table2 的数据合并到 table1 table1.Merge(table2);
注意:Merge() 会直接修改 table1。
Merge()
table1
如果不想改原表,可以这样:
DataTable result = table1.Copy(); result.Merge(table2);
如果 table2 里有 table1 没有的列,可以用:
table2
table1.Merge( table2, false, MissingSchemaAction.Add );
含义:
table1.Merge(来源表, 是否保留当前表已有修改, 缺失字段如何处理);
常见用法:
table1.Merge(table2, false, MissingSchemaAction.Add);
其中:
false:如果主键相同,来源表的数据可以覆盖目标表数据
false
MissingSchemaAction.Add:如果来源表有新列,就自动加到目标表
MissingSchemaAction.Add
也可以手动导入:
foreach (DataRow row in table2.Rows) { table1.ImportRow(row); }
ImportRow() 会保留原来的 RowState,比如 Added、Modified 等。
ImportRow()
RowState
Added
Modified
如果只是简单复制值,也可以这样:
foreach (DataRow row in table2.Rows) { DataRow newRow = table1.NewRow(); newRow.ItemArray = row.ItemArray; table1.Rows.Add(newRow); }
这个要求两个表的列数量和顺序一致。
例如两个表都有 Id 字段,希望:
Id
Id 相同:更新已有行
Id 不同:新增行
可以先设置主键:
table1.PrimaryKey = new[] { table1.Columns["Id"] }; table2.PrimaryKey = new[] { table2.Columns["Id"] }; table1.Merge(table2, false, MissingSchemaAction.Add);
示例:
DataTable table1 = new DataTable(); table1.Columns.Add("Id", typeof(int)); table1.Columns.Add("Name", typeof(string)); table1.Columns.Add("Age", typeof(int)); table1.PrimaryKey = new[] { table1.Columns["Id"] }; table1.Rows.Add(1, "张三", 20); table1.Rows.Add(2, "李四", 25); DataTable table2 = table1.Clone(); table2.PrimaryKey = new[] { table2.Columns["Id"] }; table2.Rows.Add(2, "李四-修改后", 26); table2.Rows.Add(3, "王五", 30); table1.Merge(table2, false, MissingSchemaAction.Add);
合并后 table1 大概是:
Id Name Age 1 张三 20 2 李四-修改后 26 3 王五 30
如果没有设置 PrimaryKey,Merge() 通常会把 table2 的行全部追加进去,不会自动判断哪一行是重复的。
PrimaryKey
比如来源表是:
UserId, UserName
目标表是:
Id, Name
这种就不要直接 Merge(),建议手动写:
foreach (DataRow sourceRow in table2.Rows) { DataRow targetRow = table1.NewRow(); targetRow["Id"] = sourceRow["UserId"]; targetRow["Name"] = sourceRow["UserName"]; table1.Rows.Add(targetRow); }
如果两个表结构基本一致:
如果要按某个字段去重或更新:
table1.PrimaryKey = new[] { table1.Columns["Id"] }; table1.Merge(table2, false, MissingSchemaAction.Add);
如果字段不一致、需要转换字段名或处理特殊逻辑,就用 foreach + NewRow() 手动合并。
foreach + NewRow()