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

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.

C#
DataTable dt3 = new DataTable();
var contacts = dt1.AsEnumerable().Intersect(dt2.AsEnumerable(),DataRowComparer.Default);
foreach (DataRow rows in contacts)
{
  dt3.Rows.Add(rows);
}
Posted
Updated 24-Apr-15 9:28am
v2
Comments
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:
C#
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
    dt3.Rows.Add(rowCopy);
}
 
Share this answer
 
v3
Comments
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 system.data.datasetextensions
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