Friday, August 8, 2008

Removing duplicate records from datatable in ADO.NET

private DataTable RemoveDuplicates(DataTable dt)
{
DataTable dtUnique = new DataTable();
dtUnique = dt.Clone();
DataColumn[] coln = new DataColumn[dt.Columns.Count];
dtUnique.Columns.CopyTo(coln, 0);
dtUnique.PrimaryKey = coln;
DataRow[] drs = new DataRow[dt.Rows.Count];
dt.Rows.CopyTo(drs, 0);

foreach (DataRow dr1 in drs)
{
if (dtUnique.Rows.Contains(dr1.ItemArray))
dt.Rows.Remove(dr1);
else
dtUnique.Rows.Add(dr1.ItemArray);
}
dt.Dispose();
drs = null;
coln = null;

return dtUnique;
}

No comments: