比较两个DataTables的C#差异?
可能重复:
C#,如何比较两个数据表A + B,如何显示B中但不在A中的行
我需要比较c#中的两个数据表来找出差异。 这两个数据表具有相同的模式。 最好的方法是什么? 可以使用linq查询完成吗? 如果是,怎么样?
您可以使用LINQ连接两个DataTable
对象,匹配每一列。 然后获取IQueryable
并找到前两个不在IQueryable
中的DataTable
对象中的所有行。
示例 :
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("id") equals table2.Field ("id") where table1.Field ("ColumnA") != table2.Field ("ColumnA") || table1.Field ("ColumnB") != table2.Field ("ColumnB") || table1.Field("ColumnC") != table2.Field ("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("ColumnA") equals table2.Field ("ColumnA") where table1.Field ("ColumnB") == table2.Field ("ColumnB") || table1.Field("ColumnC") == table2.Field ("ColumnC") || table1.Field
上面的代码应该可行,但我没有测试它。
您还可以在DataTable上查看LINQ查询,其中包含有关使用LINQ和DataTables的一些有用信息。
我还发现LINQ示例在编写LINQ时很有用。