Friday, 3 May 2013

C# removing duplicate records from DataTable

/// <summary>
/// Remove duplicate records from data table
/// </summary>
/// <param name="table">DataTable for removing duplicate records</param>
/// <param name="DistinctColumn">Column to check for duplicate values or records</param>
/// <returns></returns>
public DataTable RemoveDuplicateRows(DataTable table, string DistinctColumn)
{
try
{
ArrayList UniqueRecords = new ArrayList();
ArrayList DuplicateRecords = new ArrayList();
// Check if records is already added to UniqueRecords otherwise,
// Add the records to DuplicateRecords
foreach(DataRow dRow in table.Rows)
{
if (UniqueRecords.Contains(dRow[DistinctColumn]))
DuplicateRecords.Add(dRow);
else
UniqueRecords.Add(dRow[DistinctColumn]);
}
// Remove dupliate rows from DataTable added to DuplicateRecords
foreach (DataRow dRow in DuplicateRecords)
{
table.Rows.Remove(dRow);
}
// Return the clean DataTable which contains unique records.
return table;
}
catch (Exception ex)
{
return null;
}
}

No comments:

Post a Comment