2012-06-11 514 views
4

可能重複:
C#, how to compare two datatables A + B, how to show rows which are in B but not in A比較兩個DataTables在C#中的差異?

我需要比較在C#中兩個DataTable找到的差異。這兩個數據表具有相同的模式。什麼是最好的方式來做到這一點?可以使用linq查詢完成嗎?如果是,如何?

+0

什麼數據庫和版本? –

+0

如果你對sql服務器感興趣,並且擁有合適的visual studio版本 - 只需使用數據庫項目availibale – YavgenyP

+0

'DataTable'或數據庫表? – jrummell

回答

6

您可以使用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時,我也發現LINQ samples有幫助。

+0

是的,如果你能爲我提供一個例子,因爲我對linq和c相當陌生# – user1256789

+0

你走了。如果您有任何問題,請告訴我。由於設置需要一段時間,我沒有測試它們,但它們應該工作。 – Trisped

+0

感謝一噸,這看起來正是我所尋找的。讓我試試看:) – user1256789