我只是在这里发布这个以供将来参考....
如果您想使用来自 dtblToUpdateFrom 的值更新 dtblToUpdate 但您需要加入多个列,那么这似乎可行:
dtblToUpdate.Rows.Cast<DataRow>().Join(dtblToUpdateFrom.Rows.Cast<DataRow>(),
r1 => new { p1 = r1["ColToJoinOn1"], p2 = r1["ColToJoinOn2"] },
r2 => new { p1 = r2["ColToJoinOn1"], p2 = r2["ColToJoinOn2"] },
(r1, r2) => new { r1, r2 }).ToList()
.ForEach(o => o.r1.SetField("ColToUpdate", o.r2["ColToUpdateFrom"]));
如果这有什么问题,请告诉我。
更新:
这是一些测试代码,表明它可以工作:
DataTable dtblToUpdate = new DataTable();
dtblToUpdate.Columns.AddRange(new DataColumn[]{new DataColumn("ColToJoinOn1"), new DataColumn("ColToJoinOn2"), new DataColumn("ColToUpdate")});
dtblToUpdate.Rows.Add("1", "1", "nothing");
dtblToUpdate.Rows.Add("2", "1", "nothing");
dtblToUpdate.Rows.Add("3", "1", "nothing");
DataTable dtblToUpdateFrom = new DataTable();
dtblToUpdateFrom.Columns.AddRange(new DataColumn[]{new DataColumn("ColToJoinOn1"), new DataColumn("ColToJoinOn2"), new DataColumn("ColToUpdateFrom")});
dtblToUpdateFrom.Rows.Add("1", "1", "something");
dtblToUpdateFrom.Rows.Add("2", "1", "something");
dtblToUpdateFrom.Rows.Add("3", "2", "something"); //Won't be updated since ColToJoinOn2 does not match in dtlbToUpdate
Console.WriteLine("dtblToUpdate before update:");
foreach(DataRow drow in dtblToUpdate.Rows)
{
Console.WriteLine(drow["ColToJoinOn1"].ToString() + "." + drow["ColToJoinOn2"].ToString() + " - " + drow["ColToUpdate"].ToString());
}
dtblToUpdate.Rows.Cast<DataRow>().Join(dtblToUpdateFrom.Rows.Cast<DataRow>(),
r1 => new { p1 = r1["ColToJoinOn1"], p2 = r1["ColToJoinOn2"] },
r2 => new { p1 = r2["ColToJoinOn1"], p2 = r2["ColToJoinOn2"] },
(r1, r2) => new { r1, r2 }).ToList()
.ForEach(o => o.r1.SetField("ColToUpdate", o.r2["ColToUpdateFrom"]));
Console.WriteLine("dtblToUpdate after update:");
foreach(DataRow drow in dtblToUpdate.Rows)
{
Console.WriteLine(drow["ColToJoinOn1"].ToString() + "." + drow["ColToJoinOn2"].ToString() + " - " + drow["ColToUpdate"].ToString());
}
输出:
dtblToUpdate before update:
1.1 - nothing
2.1 - nothing
3.1 - nothing
dtblToUpdate after update:
1.1 - something
2.1 - something
3.1 - nothing
此外,当一个表缺少金额列时,请参阅此帖子以获取另一种选择。您可以在一列上连接表并获得一个新的 DataTable,其中包含两个表之间的所有唯一列: 如何在 c# 中左外连接两个 DataTable?