使用 LINQ 比较两个数据表
我有两个数据库。它们都使用 GetTable1 \ GetTable2 函数填充到 DataTables 中。
我想要做的基本上是使用 LINQ 比较数据表。
我已经尝试过:
var infoQuery =
(from db1 in GetTable1().AsEnumerable()
select db1).Except
(from db2 in GetTable2().AsEnumerable()
select db2);
也尝试过: (看起来应该和上面做的一样):
var results = GetTable1().AsEnumerable().Except(GetTable2().AsEnumerable());
我得到的结果是一张表中的所有记录。我正在寻找 1 的返回值,因为两个数据库之间有 1 行不同。
我正在使用 Object 中的默认 Equals 方法,我是否需要重写该实现才能使其正常工作?
I have two Databases. They are both filled into DataTables using the GetTable1 \ GetTable2 functions.
What I am looking to do is to basically compare the datatables using LINQ.
I Have tried :
var infoQuery =
(from db1 in GetTable1().AsEnumerable()
select db1).Except
(from db2 in GetTable2().AsEnumerable()
select db2);
Also tried :
(Looks like it should be doing same as above ) :
var results = GetTable1().AsEnumerable().Except(GetTable2().AsEnumerable());
The results I get back are all the records in one table. I am looking for a return of 1 since 1 row is different between the two databases.
I am using default Equals method from Object , do I need to override that implementation to get this to work?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
它与行的比较方式有关。它们的值不会与参考值进行比较。
http://msdn.microsoft.com/en-us/library/bb300779.aspx
来自 MSDN 的示例:
It has to do with the way the rows are compared. Their values are not compared their references are.
http://msdn.microsoft.com/en-us/library/bb300779.aspx
Example from MSDN:
即使它们可能具有相同的列,但 table1 中的单个数据行与 table2 中的行不匹配。所以 row_of_table1 != row_of_table2 始终为 true。您必须提供附加信息来比较它们(可能使用两个表都唯一的标识符)。 答案在这里。
Nate Zaugg 已经发布了它们不匹配的原因
Even though they might have the same columns a single data row from table1 does not match a row from table2. So row_of_table1 != row_of_table2 is always true. You must provide additional information to compare them ( maybe with an identifier that is unique to both tables ). One approach you could use as a starting point is described in an answer here.
The reason why they do not match is already posted by Nate Zaugg