比较两个数据表在 C# 中的差异

本文关键字:数据表 两个 比较 | 更新日期: 2023-09-27 18:36:45

可能的重复项:
C#,如何比较两个数据表 A + B,如何显示 B 中但不在 A 中的行

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

比较两个数据表在 C# 中的差异

可以使用

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.
}

上面的代码应该可以工作,尽管我没有测试它。

您还可以查看 DataTable 上的 LINQ 查询,其中包含有关将 LINQ 与 DataTable 配合使用的一些有用信息。
我还发现 LINQ 示例在编写 LINQ 时很有帮助。