我一直試圖找到一種方法,做了一段時間的DataTable比較和最後寫了我自己的功能,這裏是我的了:
bool tablesAreIdentical = true;
// loop through first table
foreach (DataRow row in firstTable.Rows)
{
foundIdenticalRow = false;
// loop through tempTable to find an identical row
foreach (DataRow tempRow in tempTable.Rows)
{
allFieldsAreIdentical = true;
// compare fields, if any fields are different move on to next row in tempTable
for (int i = 0; i < row.ItemArray.Length && allFieldsAreIdentical; i++)
{
if (!row[i].Equals(tempRow[i]))
{
allFieldsAreIdentical = false;
}
}
// if an identical row is found, remove this row from tempTable
// (in case of duplicated row exist in firstTable, so tempTable needs
// to have the same number of duplicated rows to be considered equivalent)
// and move on to next row in firstTable
if (allFieldsAreIdentical)
{
tempTable.Rows.Remove(tempRow);
foundIdenticalRow = true;
break;
}
}
// if no identical row is found for current row in firstTable,
// the two tables are different
if (!foundIdenticalRow)
{
tablesAreIdentical = false;
break;
}
}
return tablesAreIdentical;
相比戴夫馬克爾的解決方案,我的治療兩張記錄相同,但順序不同的表格。希望這可以幫助任何人再次絆倒這個線程。
我建議加上「的ToString」方法這樣既相同否則返回false:`如果(T1。行[i] [dc.ColumnName] .ToString()!= t2.Rows [i] [dc.ColumnName] .ToString())`。比較可能會給出錯誤的答案35!= 35. – GoRoS 2012-01-27 21:04:07
答案http://stackoverflow.com/a/7518099/52277也比較列數 – 2013-08-23 23:57:19