【问题标题】:Compare two DataTables for differences in C#? [duplicate]比较两个数据表在 C# 中的差异? [复制]
【发布时间】:2012-06-11 17:00:27
【问题描述】:

可能重复:
C#, how to compare two datatables A + B, how to show rows which are in B but not in A

我需要比较 c# 中的两个数据表以找出差异。这两个数据表具有相同的架构。最好的方法是什么?可以使用 linq 查询来完成吗?如果是,如何?

【问题讨论】:

  • 如果您正在谈论 sql server,并且拥有适当版本的 Visual Studio - 只需使用那里可用的数据库项目
  • DataTables 还是数据库表?
  • 我指的是c#中的DataTable。

标签: c# linq datatable


【解决方案1】:

您可以使用 LINQ 连接两个 DataTable 对象,匹配每一列。然后取IQueryable 并找出前两个DataTable 对象中所有不在IQueryable 中的行。

示例

private void SampleSolution(DataTable dt1, DataTable dt2)
{
    //If you have primary keys:
    var results = from table1 in dt1.AsEnumerable()
                    join table2 in dt2.AsEnumerable() on table1.Field<int>("id") equals table2.Field<int>("id")
                    where table1.Field<int>("ColumnA") != table2.Field<int>("ColumnA") || table1.Field<int>("ColumnB") != table2.Field<int>("ColumnB") || table1.Field<String>("ColumnC") != table2.Field<String>("ColumnC")
                    select table1;
    //This will give you the rows in dt1 which do not match the rows in dt2.  You will need to expand the where clause to include all your columns.


    //If you do not have primarry keys then you will need to match up each column and then find the missing.
    var matched = from table1 in dt1.AsEnumerable()
                    join table2 in dt2.AsEnumerable() on table1.Field<int>("ColumnA") equals table2.Field<int>("ColumnA")
                    where table1.Field<int>("ColumnB") == table2.Field<int>("ColumnB") || table1.Field<string>("ColumnC") == table2.Field<string>("ColumnC") || table1.Field<object>("ColumnD") == table2.Field<object>("ColumnD")
                    select table1;
    var missing = from table1 in dt1.AsEnumerable()
                    where !matched.Contains(table1)
                    select table1;
    //This should give you the rows which do not have a match.  You will need to expand the where clause to include all your columns.
}

上面的代码应该可以工作,虽然我没有测试过。

您还可以查看LINQ query on a DataTable,其中包含一些关于将 LINQ 与 DataTables 结合使用的有用信息。
我还发现LINQ samples 在编写 LINQ 时很有帮助。

【讨论】:

  • 是的,如果你能给我一个例子,那就太好了,因为我对 linq 和 c# 很陌生
  • 你去。如果您有任何问题,请告诉我。由于设置需要一段时间,我没有测试它们,但它们应该可以工作。
  • 非常感谢,这看起来正是我想要的。让我试一试:)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-11-23
  • 2017-07-11
相关资源
最近更新 更多