两个数据表与不同的主键集合并
本文关键字:合并 集合 两个 数据表 | 更新日期: 2023-09-27 17:56:03
我有两个数据表,如下所示
TableA
-------------------------------------------
ParamId | Code | Val | date_time
-------------------------------------------
1 A1 5.6 02.04.2014 00:00
1 A1 10 02.04.2014 01:00
1 A1 5.9 02.04.2014 02:00
1 A1 8 02.04.2014 03:00
1 A1 7 02.04.2014 04:00
1 A1 12 02.04.2014 05:00
TableB
-------------------------------------------
ParamId | Code | Val | date_time
-------------------------------------------
1 A2 5.6 02.04.2014 00:00
1 A2 10 02.04.2014 01:00
1 A2 5.9 02.04.2014 02:00
1 A2 8 02.04.2014 03:00
1 A2 7 02.04.2014 04:00
1 A2 12 02.04.2014 05:00
Expected result:
-------------------------------------------
ParamId | Code | Val | date_time
-------------------------------------------
1 A1 5.6 02.04.2014 00:00
1 A1 10 02.04.2014 01:00
1 A1 5.9 02.04.2014 02:00
1 A1 8 02.04.2014 03:00
1 A1 7 02.04.2014 04:00
1 A1 12 02.04.2014 05:00
1 A2 5.6 02.04.2014 00:00
1 A2 10 02.04.2014 01:00
1 A2 5.9 02.04.2014 02:00
1 A2 8 02.04.2014 03:00
1 A2 7 02.04.2014 04:00
1 A2 12 02.04.2014 05:00
即表A具有来自列dt的主键,结果表具有来自列dt和代码的主键。我尝试 TableA.Merge(TableB);比循环中的 ResultTable.Merge(TableA)。但是在结果表中,我只有最后合并的表值。
您需要定义一个空的合并目标表,并将所有其他表合并到该合并表中。因此,不要预先合并任何表。您的代码如下所示,数据表merged
保存最终结果。在Merge
方法中,我使用 MissingSchemaAction.Ignore
来防止由提供的数据集中的主键列之间可能存在的不匹配而导致的 nullreference异常。
var one = BuildDataTable();
one.PrimaryKey = new DataColumn[] { one.Columns["code"]};
var row = one.NewRow();
row["id"] = "1";
row["code"] = 1;
row["val"] = 5.6;
row["date_time"] = DateTime.Now;
one.Rows.Add(row);
var two = BuildDataTable();
two.PrimaryKey = new DataColumn[] { two.Columns["date_time"] , two.Columns["code"]};
row = two.NewRow();
row["id"] = "1";
row["code"] = 2;
row["val"] = 3.0;
row["date_time"] = DateTime.Now.AddDays(1);
two.Rows.Add(row);
// merge table result
var merged = BuildDataTable();
merged.PrimaryKey = new DataColumn[] {
merged.Columns["date_time"] ,
merged.Columns["code"]};
// for each table call merge on our merged table
merged.Merge(one, true, MissingSchemaAction.Ignore);
merged.Merge(two, true, MissingSchemaAction.Ignore);
// continue calling Merge until all tables are done
构建表的帮助程序方法
private DataTable BuildDataTable()
{
var dt = new DataTable();
//ParamId | Code | Val | date_time
dt.Columns.Add("id", typeof(string));
dt.Columns.Add("code", typeof(int));
dt.Columns.Add("val", typeof(double));
dt.Columns.Add("date_time", typeof(DateTime));
return dt;
}