可能重复:
C#, how to compare two datatables A + B, how to show rows which are in B but not in A
我需要比较c#中的两个数据表来找出差异。这两个数据表具有相同的模式。最好的方法是什么?可以使用linq查询吗?如果是,怎么样?
答案 0 :(得分:7)
您可以使用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.
}
内的所有行。
示例强>:
{{1}}
上面的代码应该可行,但我没有测试它。
您还可以查看LINQ query on a DataTable,其中包含有关使用LINQ和DataTables的一些有用信息 我还发现LINQ samples在编写LINQ时很有帮助。