C#语言判断两个数据表的内容是否相同

判断两个数据表的内容是否相同

源代码:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
public static bool EqualsByContent(this DataTable thisDataTable, DataTable otherDataTable)
{
// Compare row count.
if (thisDataTable.Rows.Count != otherDataTable.Rows.Count)
{
return false;
}

// Compare column count.
if (thisDataTable.Columns.Count != otherDataTable.Columns.Count)
{
return false;
}

// Compare data in each cell of each row.
for (int i = 0; i < thisDataTable.Rows.Count; i++)
{
for (int j = 0; j < thisDataTable.Columns.Count; j++)
{
if (!thisDataTable.Rows[i][j].Equals(otherDataTable.Rows[i][j]))
{
return false;
}
}
}

// The two DataTables contain the same data.
return true;
}

示例:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
// Create two DataTable objects.
var dataTable1 = new DataTable();
var dataTable2 = new DataTable();

// Create two columns in each DataTable.
dataTable1.Columns.Add("Column1");
dataTable2.Columns.Add("Column1");
dataTable1.Columns.Add("Column2");
dataTable2.Columns.Add("Column2");

// Add one row to each DataTable.
dataTable1.Rows.Add(new object[] { "Hello World", DateTime.Today });
dataTable2.Rows.Add(new object[] { "Hello World", DateTime.Today.AddYears(1) });

// Write results.
// Expected result is false.
Console.WriteLine(dataTable1.EqualsByContent(dataTable2));
Your browser is out-of-date!

Update your browser to view this website correctly. Update my browser now

×