How to remove duplicate row from a DataTable

Today in my development procedure I want to remove duplicate rows from DataTable. There is a lot of solution in community. But I think that I need to make the solution for flexibility of use.
Now I want to shared this with you. Hope that it will helpful for others developers.

First Solution:

public DataTable RemoveDuplicateRows(DataTable dTable, string colName)
Hashtable hTable = new Hashtable();
ArrayList duplicateList = new ArrayList();

//Add list of all the unique item value to hashtable, which stores combination of key, value pair.
//And add duplicate item value in arraylist.
foreach (DataRow drow in dTable.Rows)
if (hTable.Contains(colName==""?drow[0]:drow[colName]))
hTable.Add(colName==""?drow[0]:drow[colName], string.Empty);

//Removing a list of duplicate items from datatable.
foreach (DataRow dRow in duplicateList)

//Datatable which contains unique records will be return as output.
return dTable;

we can call this method

RemoveDuplicateRows(dataTable,""); or

Second Solution:

private void btnRemove_Click(object sender, EventArgs e)
List keyColumns = new List();
RemoveDuplicates(ref dtAlarmData, keyColumns);

//Method to remove Duplicate value from DataTable

public static void RemoveDuplicatesFromDataTable(ref DataTable table, List keyColumns)
Dictionary uniquenessDict = new Dictionary(table.Rows.Count);
StringBuilder stringBuilder = null;
int rowIndex = 0;
DataRow row;
DataRowCollection rows = table.Rows;
while (rowIndex < rows.Count - 1) { row = rows[rowIndex]; stringBuilder = new StringBuilder(); foreach (string colname in keyColumns) { //If no column name found it will check the first column by default. stringBuilder.Append(colname==""?((string)row[0]):((string)row[colname]));

if (uniquenessDict.ContainsKey(stringBuilder.ToString()))
uniquenessDict.Add(stringBuilder.ToString(), string.Empty);


Popular posts from this blog

The model backing the 'MyDBContext' context has changed since the database was created. Either manually delete/update the database, or call Database.SetInitializer with an IDatabaseInitializer instance. For example, the DropCreateDatabaseIfModelChanges strategy will automatically delete and recreate the database, and optionally seed it with new data.

How can I get a value of a property from an anonymous type (C#)

Check/Uncheck all items in a CheckBoxList using Javascript