I just want to tell everyone that what is most widely circulated on the Internet is not necessarily correct.
I want to search Google on how to determine whether two DataTables are equal. The most common method that comes up is the following method.
code
private bool ValueEquals(DataTable objA,DataTable objB)
{
if(objA != null && objB != null)
{
if(objA.Rows.Count != objB.Rows.Count)
{
return false;
}
if(objA.Columns.Count != objB.Columns.Count)
{
return false;
}
}
DataView dv = new DataView(objB);
string keys = "";
foreach(DataColumn col in objA.Columns)
{
keys += ","+col.ColumnName;
}
dv.Sort = keys.Substring(1);
foreach(DataRow row in objA.Rows)
{
if(row.RowState != DataRowState.Deleted)
{
if(dv.Find(row.ItemArray)<0)
{
return false;
}
}
else
{
return false;
}
}
return true;
}
The originator of this piece of code cannot be verified, but there are many rumors.
I don’t know if the person who reprinted it has verified the correctness of this method, or if he just reprinted it.
This method is actually wrong.
If two DataTables have the same number of rows and columns, but the first row is the same and the second row is different, the comparison method above will still return True.
I write here to tell the majority of people (including me) that what is most circulated on the Internet is not necessarily correct. I also want to say something to the veterans. Please verify the correctness of the content when reprinting it. I think it is good for myself no matter what. , it’s all good for others.
This is my first time posting. If what I say is wrong, I hope you won’t suggest it.
I also hope that an expert can provide a correct and efficient method to compare whether two DataTables are equal.
I used a more old-fashioned method
code
public bool DataTableTheSame(DataTable Table1, DataTable Table2)
{
if (Table1 == null || Table2 == null)
{
return false;
}
if (Table1.Rows.Count != Table2.Rows.Count)
{
return false;
}
if (Table1.Columns.Count != Table2.Columns.Count)
{
return false;
}
for (int i = 0; i < Table1.Rows.Count; i++)
{
for (int j = 0; j < Table1.Columns.Count; j++)
{
if (Table1.Rows[i][j].ToString() != Table2.Rows[i][j].ToString())
{
return false;
}
}
}
return true;
}