
DataTables sometimes have equal rows. How can you compare these rows between tables? With the C# code in this example, we loop over both DataTables in nested foreach-loops to demonstrate how you can do this effectively.
This C# example code uses SequenceEqual to compare DataTable rows.

DataTables don't have any built-in methods for complicated comparison operations. Here, we introduce the CompareRows method: it receives two DataTable instances. Then, it loops over all the rows in both DataTables with nested loops. In the inner block, we access the ItemArray property on both DataRow instances at the present position.
We use SequenceEqual from System.Linq to determine if the arrays are exactly equal in length and element composition. If your comparison requirements are different, you can analyze each element in a for-loop.
SequenceEqual MethodProgram that compares DataTable rows [C#]
using System;
using System.Data;
using System.Linq;
class Program
{
static void CompareRows(DataTable table1, DataTable table2)
{
foreach (DataRow row1 in table1.Rows)
{
foreach (DataRow row2 in table2.Rows)
{
var array1 = row1.ItemArray;
var array2 = row2.ItemArray;
if (array1.SequenceEqual(array2))
{
Console.WriteLine("Equal: {0} {1}", row1["Drug"], row2["Drug"]);
}
else
{
Console.WriteLine("Not equal: {0} {1}", row1["Drug"], row2["Drug"]);
}
}
}
}
static DataTable GetTable1()
{
DataTable table = new DataTable();
table.Columns.Add("Dosage", typeof(int));
table.Columns.Add("Drug", typeof(string));
table.Columns.Add("Patient", typeof(string));
table.Rows.Add(25, "Indocin", "David");
table.Rows.Add(50, "Enebrel", "Cecil");
return table;
}
static DataTable GetTable2()
{
DataTable table = new DataTable();
table.Columns.Add("Dosage", typeof(int));
table.Columns.Add("Drug", typeof(string));
table.Columns.Add("Patient", typeof(string));
table.Rows.Add(21, "Combivent", "Janet");
table.Rows.Add(50, "Enebrel", "Cecil");
table.Rows.Add(10, "Hydralazine", "Christoff");
return table;
}
static void Main()
{
CompareRows(GetTable1(), GetTable2());
}
}
Output
Not equal: Indocin Combivent
Not equal: Indocin Enebrel
Not equal: Indocin Hydralazine
Not equal: Enebrel Combivent
Equal: Enebrel Enebrel
Not equal: Enebrel HydralazineResults. The program's result is correct: it determines that each DataTable has a DataRow with the medication name "Enebrel" and a dosage of 50 mg. Looking at the data construction logic, we can see that that is the only equal row in both DataTables. To further test the logic, try changing the data GetTable1() and GetTable2() to add more or fewer equal rows.
Note: All fields must be equal for rows to be considered equal.

The rows in DataTables can be compared using the declarative syntax of the SequenceEquals method. You can also use imperative testing logic to determine the equality or near-equality of two DataRows with the elements in the ItemArray property. With this method, you can determine similarities in discrete data structures.
Data