ExtensionMethod.NET Home of 880 C#, Visual Basic, F# and Javascript extension methods

EqualsByContent

Checks if two DataTable objects have the same content.

Source

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;
}

Example

// 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));

Author: Jonas Butt

Submitted on: 24 aug. 2008

Language: C#

Type: System.Data.DataTable

Views: 5588