如何获得两个DataTable之间的区别 [英] How to get difference between two DataTables
本文介绍了如何获得两个DataTable之间的区别的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有这两个DataTable和我想要得到它们之间的区别。下面是一个例子:
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到使用这两个类似的解决方案,但它总是返回表1和表1没有,表2。这是第一个解决方案:
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);
解决方法二:
Second solution:
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();
这篇关于如何获得两个DataTable之间的区别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文