I have 2 DataTable and I want to create a third DataTable that contais the difference between DataTable 1 and DataTable 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 ?
Answers:
Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.
Method 1
Try something like this:
table1.Merge(table2); DataTable changesTable = table1.GetChanges();
Method 2
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
Method 3
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.
All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0