how to find difference row between two tables in c#.net

Here is the sample code, using you can finding the difference.

You need to pass two table reference in below function and it return the final difference table with containing difference row.

public DataTable CompareDataTables(DataTable first, DataTable second)
{
first.TableName = "FirstTable";
second.TableName = "SecondTable";

//Create Empty Table
DataTable table = new DataTable("Difference");

try
{
//Must use a Dataset to make use of a DataRelation object
using (DataSet ds = new DataSet())
{
//Add tables
ds.Tables.AddRange(new DataTable[] { first.Copy(), second.Copy() });

//Get Columns for DataRelation
DataColumn[] firstcolumns = new DataColumn[1];

for (int i = 0; i < ds.Tables[0].Columns.Count; i++)
{
if (ds.Tables[0].Columns[i].ColumnName == "RefNumber")
firstcolumns[0] = ds.Tables[0].Columns[i];
}

DataColumn[] secondcolumns = new DataColumn[1];

for (int i = 0; i < ds.Tables[1].Columns.Count; i++)
{
if (ds.Tables[1].Columns[i].ColumnName == "RefNumber")
secondcolumns[0] = ds.Tables[1].Columns[i];
}

//Create DataRelation
DataRelation r = new DataRelation(string.Empty, firstcolumns, secondcolumns, false);

ds.Relations.Add(r);

//Create columns for return table
for (int i = 0; i < first.Columns.Count; i++)
{
table.Columns.Add(first.Columns[i].ColumnName, first.Columns[i].DataType);
}

//If First Row not in Second, Add to return table.
table.BeginLoadData();

foreach (DataRow parentrow in ds.Tables[0].Rows)
{
DataRow[] childrows = parentrow.GetChildRows(r);
if (childrows == null || childrows.Length == 0)
table.LoadDataRow(parentrow.ItemArray, true);
}

table.EndLoadData();

}
}
catch (Exception ex)
{
throw ex;
}

return table;
}


Happy Coding....

No comments:

Post a Comment