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.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
{
Dictionary
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++;
}
}
}
No comments:
Post a Comment