开发者

Difference Between 2 DataTable

I have 2 DataTable and I want to create a third DataTable that contais the difference between DataTable 1 and DataTable开发者_Go百科 2.

For example, DataTable1 has the original data, and the DataTable 2 is just a copy, like a replication. But when you insert a new row in DataTable1, the DataTable2 has just insert the same row. Nowaday my code do a compare between DataTable1 and DataTable2, if not equals (1 row or more was inserted), DataTable2 record all data from DataTable1 again.

How can I do a select command, that do this difference and record those datas in a third DataTable ?


Try something like this:

table1.Merge(table2); 
DataTable changesTable = table1.GetChanges(); 


I will consider that there are two columns to identify the tables(col1,col2)

var rowsOnlyInDt1 = dt1.AsEnumerable().Where(r => !dt2.AsEnumerable()
                    .Any(r2 => r["col1"].Trim().ToLower() == r2["col1"].Trim().ToLower() && r["col2"].Trim().ToLower() == r2["col2"].Trim().ToLower()));

DataTable result = rowsOnlyInDt1.CopyToDataTable();//The third table


Using only SQL you can use UNION to easily find differences, there is an excellent article on the subject here: http://weblogs.sqlteam.com/jeffs/archive/2004/11/10/2737.aspx

The query will return an empty row set when the tables match, otherwise the differing rows are returned.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜