compare datarows of different tables

Sandy picture Sandy · Jan 30, 2012 · Viewed 14.3k times · Source

I posted a similar query some time ago and decided to trim down the complexity of it to let developers answer my main problem. It could be stated as duplicate, but still I want to post it as editing the previous post did not yield much result.

I have 2 datatables: dataTable1 and dataTable2. Both have 1 row with same entries. For eg. columns in both the datatables are Name, Class, Subject. Now both row of both the dataTable are same with values ("John", "5", "Science"). Now I want to compare thses 2 rows if they they have same entries or not. I tried for:

if(dataTable1.Rows[0].GetHashCode() == dataTable2.Rows[0].GetHashCode()) 
{ 
    // Result is false (but I expected it to be true) 
} 

And also tried:

if(dataTable1.Rows[0].ItemArray == dataTable2.Rows[0].ItemArray) 
{ 
    // Result is false (but I expected it to be true) 
} 

I want to avoid loops to do it, but if needed thats fine. I just want to compare the 2 rows of 2 different dataTables that if their entries are same or not. And I am not sure how to proceed. Thanks.

Answer

Dave Watts picture Dave Watts · Jan 30, 2012

You could use the Equals method of the DataRowComparer class to compare the rows.