compare datarows of different tables
Solution 1
var result= dataTable1.AsEnumerable().Intersect(dataTable2.AsEnumerable(),
DataRowComparer.Default);
it returns the records that are in both the table
more info at:
http://msdn.microsoft.com/en-us/library/bb386998.aspx
Solution 2
Using SequenceEqual to compare two data row as in the following example
foreach (DataRow dr in datatable1.Rows)
foreach (DataRow dr2 in datatable2.Rows)
{
if (dr.ItemArray.SequenceEqual(dr2.ItemArray))
{
MessageBox.Show("dr = dr2");
//statement
}
else
{
MessageBox.Show("dr != dr2");
//statement
}
}
Solution 3
You could use the Equals
method of the DataRowComparer
class to compare the rows.
Solution 4
For simplicity, I would normally just cast the item in the ItemArray
to a string and compare them that way.
From what I remember, using the GetHashCode will not bring out the same result as you will find many others will say.
If you have a large number of rows, then you could try creating a class that inherits from DataRow
and override the Equals method. For example:
class CustomRow : DataRow
{
public override bool Equals(object obj)
{
if(obj.GetType() != typeof(CustomRow)) return false;
for (int i = 0; i < ItemArray.Length; i++)
if (((CustomRow)obj)[i] != this[i])
return false;
return true;
}
}
Sandy
Enthusiast in technology world and fascinated by new entrepreneurs. Strongly believe in innovation and creativity and looking forward to be a part of it.
Updated on June 25, 2022Comments
-
Sandy almost 2 years
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.