比较数据表和返回行与更改 [英] Compare datatable and return rows with changes

查看:74
本文介绍了比较数据表和返回行与更改的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述





我试图通过使用下面的代码比较两个数据表和返回的行,但它不起作用。我需要比较 dt1 & dt2 ,请提示一些选项。



Hi,

I am trying to compare two datatable and return rows which has changes by using the below code and it doesn't work. I need to compare dt1 & dt2, Pls suggest some options.

DataTable dt3 = new DataTable();
var contacts = dt1.AsEnumerable().Intersect(dt2.AsEnumerable(),DataRowComparer.Default);
foreach (DataRow rows in contacts)
{
  dt3.Rows.Add(rows);
}

推荐答案

如果我正确理解你的问题,你的DataTables具有相同的Column-schema,你想得到那些它们没有共同的行。



- 您当前的代码与DataTables的行相交,返回DataTables共有的那些行。相反,你必须将一个表中缺少的行与另一个表中缺少的行联合起来。



- 要将DataRows复制到新的DataTable,目标DataTable具有要拥有相同的Column-schema,你必须复制DataRow,因为如果DataRow已经属于另一个DataTable,你就无法将DataRow添加到DataTable中。



这对你有用:

If I understand your question correctly, your DataTables have the same Column-schema and you want to get those rows that they do not have in common.

- Your current code intersects the rows of the DataTables, returning those rows that the DataTables have in common. Instead you have to union the rows that that are missing from one table with those missing from the other.

- To copy DataRows to a new DataTable, the destination DataTable has to have the same Column-schema and you have to make a copy of the DataRow because you can't add a DataRow to a DataTable if it already belongs to another DataTable.

This will work for you:
var dt1Rows = dt1.AsEnumerable();
var dt2Rows = dt2.AsEnumerable();
var comparer = DataRowComparer.Default;

// get the rows that dt1 and dt2 not have in common:
var diffRows = dt1Rows.Except(dt2Rows, comparer).Union(dt2Rows.Except(dt1Rows, comparer));

DataTable dt3 = dt1.Clone();  // create a new DataTable with same Column-schema

foreach (DataRow diffRow in diffRows)
{
    DataRow rowCopy = dt3.NewRow();         // new empty row
    rowCopy.ItemArray = diffRow.ItemArray;  // copy values
    dt3.Rows.Add(rowCopy);
}


这篇关于比较数据表和返回行与更改的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆