Click here to Skip to main content
15,936,850 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:

I am trying to compare two datatable and return rows which has changes by using the below code and it doesn't work. I need to compare dt1 & dt2, Pls suggest some options.

DataTable dt3 = new DataTable();
var contacts = dt1.AsEnumerable().Intersect(dt2.AsEnumerable(),DataRowComparer.Default);
foreach (DataRow rows in contacts)
Updated 24-Apr-15 9:28am
Maciej Los 24-Apr-15 15:29pm    
What you mean by "compare"? How your data look like?

1 solution

If I understand your question correctly, your DataTables have the same Column-schema and you want to get those rows that they do not have in common.

- Your current code intersects the rows of the DataTables, returning those rows that the DataTables have in common. Instead you have to union the rows that that are missing from one table with those missing from the other.

- To copy DataRows to a new DataTable, the destination DataTable has to have the same Column-schema and you have to make a copy of the DataRow because you can't add a DataRow to a DataTable if it already belongs to another DataTable.

This will work for you:
var dt1Rows = dt1.AsEnumerable();
var dt2Rows = dt2.AsEnumerable();
var comparer = DataRowComparer.Default;

// get the rows that dt1 and dt2 not have in common:
var diffRows = dt1Rows.Except(dt2Rows, comparer).Union(dt2Rows.Except(dt1Rows, comparer));

DataTable dt3 = dt1.Clone();  // create a new DataTable with same Column-schema

foreach (DataRow diffRow in diffRows)
    DataRow rowCopy = dt3.NewRow();         // new empty row
    rowCopy.ItemArray = diffRow.ItemArray;  // copy values
Share this answer
Maciej Los 24-Apr-15 15:30pm    
Sascha, do not forget to notify me if OP mark your answer as a solution. I'll promise to upvote it, MindReader ;)
Sascha Lefèvre 24-Apr-15 15:53pm    
Will do ;)
Maciej Los 24-Apr-15 15:58pm    
Why will i have to wait? ;)
Strong 5!
Sascha Lefèvre 24-Apr-15 16:01pm    
Hehe, thank you, Maciej! :)
Member 14588284 2-May-21 13:51pm    
hi i added
but i get error in theeselines
Dim dt1Rows = dt1.AsEnumerable()
Dim dt2Rows = dt2.AsEnumerable()
Dim comparer = DataRowComparer.Default

can u send me an example file please :)

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900