如何获得两个数据表之间的差异 [英] How to get difference between two DataTables
本文介绍了如何获得两个数据表之间的差异的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有这两个数据表,我想知道它们之间的区别.下面是一个例子:
I have these two datatables and I want to get the difference between them. Here is an example:
Table1
-------------------------
ID | Name
--------------------------
1 | A
2 | B
3 | C
--------------------------
Table2
-------------------------
ID | Name
--------------------------
1 | A
2 | B
--------------------------
我只想将结果作为表 1 中而不是表 2 中的数据(表 1-表 2)
I just want the result as data which is in table1 and not in table2 (table1-table2)
ResultTable
-------------------------
ID | Name
--------------------------
3 | C
--------------------------
我尝试通过 Linq 使用这两个类似的解决方案,但它总是返回 table1 而不是 table1-table2.这是第一个解决方案:
I tried to use these two similar solutions via Linq, but it always return table1 and not table1-table2. Here is first solution:
DataTable table1= ds.Tables["table1"];
DataTable table2= ds.Tables["table2"];
var diff= table1.AsEnumerable().Except(table2.AsEnumerable(),DataRowComparer.Default);
第二种解决方案:
var dtOne = table1.AsEnumerable();
var dtTwo = table2.AsEnumerable();
var difference = dtOne.Except(dtTwo);
那么,错误在哪里?非常感谢您的所有回答.:)
So, where is the mistake? Thank you a lot for all your answers. :)
推荐答案
可以试试下面的代码...
You can try the following code...
table1.AsEnumerable().Where(
r =>!table2.AsEnumerable().Select(x=>x["ID"]).ToList().Contains(r["ID"])).ToList();
这篇关于如何获得两个数据表之间的差异的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文