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]))
duplicateList.Add(drow);
else
hTable.Add(colName==""?drow[0]:drow[colName], string.Empty);
}

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

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

we can call this method

RemoveDuplicateRows(dataTable,""); or
RemoveDuplicateRows(dataTable,"word");

Second Solution:

private void btnRemove_Click(object sender, EventArgs e)
{
List keyColumns = new List();
keyColumns.Add("ColumnName1");
keyColumns.Add("ColumnName2");
keyColumns.Add("ColumnName3");
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()))
{
rows.Remove(row);
}
else
{
uniquenessDict.Add(stringBuilder.ToString(), string.Empty);
rowIndex++;
}
}
}

Comments

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.

"This request has been blocked because sensitive information could be disclosed to third party web sites when this is used in a GET request. To allow GET requests, set JsonRequestBehavior to AllowGet."

Check/Uncheck all items in a CheckBoxList using Javascript