我有两个数据表,首先包含
DataTable dtMaterialStatement = new DataTable();
dtMaterialStatement.Columns.Add(new DataColumn("MaterialNo", Type.GetType("System.String")));
dtMaterialStatement.Columns.Add(new DataColumn("MaterialId", Type.GetType("System.String")));
dtMaterialStatement.Columns.Add(new DataColumn("Qty", Type.GetType("System.Double")));
dtMaterialStatement.Columns.Add(new DataColumn("Unit", Type.GetType("System.String")));
dtMaterialStatement.Columns.Add(new DataColumn("SinglePrice", Type.GetType("System.Decimal")));
dtMaterialStatement.Columns.Add(new DataColumn("PricePerPack", Type.GetType("System.Decimal")));
dtMaterialStatement.Columns.Add(new DataColumn("UnitsPerPack", Type.GetType("System.String")));
dtMaterialStatement.Columns.Add(new DataColumn("Discount1", Type.GetType("System.Decimal")));
dtMaterialStatement.Columns.Add(new DataColumn("Discount2", Type.GetType("System.Decimal")));
dtMaterialStatement.Columns.Add(new DataColumn("Discount3", Type.GetType("System.Decimal")));
dtMaterialStatement.Columns.Add(new DataColumn("SalesPrice", Type.GetType("System.Decimal")));
dtMaterialStatement.Columns.Add(new DataColumn("Exist", Type.GetType("System.Boolean")));
第二个包含: -
"MaterialNo"
Qty
"Unit"
"SinglePrice"
"PricePerPack"
"UnitsPerPack"
"Discount1"
"Discount2"
"Discount3"
"SalesPrice"
来额外的专栏,
我想合并两个表,如果第一个表格的MaterialNo与第二个表的MaterialNo列相同,则从第二个表中获取公共列字段值以更新第一个值对应列的值。 否则在第一个表中插入一个新行,首先使用表的列,但从第二个表中获取值。
答案 0 :(得分:0)
使用此选项提取仅包含差异的新数据表http://kodesharp.blogspot.com/2007/12/c-compare-2-datatables-and-return-3rd.html
然后使用foreach
或for
循环手动将差异提取到数组中。然后将它重新插入数据表
这样的事情:
DataTable dt = CompareDataTables(dt1, dt2);
ArrayList Errors = new ArrayList();
for (int i = 0; i < d.Columns.Count; i++)
{
for (int j = 0; j < d.Rows.Count; j++)
{
if (dt1.Rows[j][i].ToString() != dt2.Rows[j][i].ToString())
{
Errors.Add(j);
Errors.Add(i);
Errors.Add(dt1.Rows[j][i].ToString());
Errors.Add(dt2.Rows[j][i].ToString());
}
}
}
DataTable dtFinal = dt;
for (int i = 0; i < Errors.Count; i += 4)
{
int ak = Int32.Parse(Errors[i].ToString());
int bk = Int32.Parse(Errors[i + 1].ToString());
dtFinal.Rows[ak][bk] = Errors[i + 2].ToString() + "/" + Errors[i + 3].ToString();
}