.NET Tutorials, Forums, Interview Questions And Answers
Welcome :Guest
 
Sign In
Register
 
Win Surprise Gifts!!!
Congratulations!!!


Top 5 Contributors of the Month
david stephan

Home >> Code Snippets >> ADO.NET >> Post New Resource Bookmark and Share   

 Subscribe to Code Snippets

Remove duplicate rows value from DataTable

Posted By:Rahul       Posted Date: October 08, 2008    Points: 10    Category: ADO.NET    URL: http://www.dotnetspark.com  
 

Below is the code to remove duplicate rows from DataTable using C#. To use this function call in the which ever event you want like this.

private void btnRemove_Click(object sender, EventArgs e)
{

List<string> keyColumns = new List<string>();

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<string> keyColumns)
{

Dictionary<string, string> uniquenessDict = new Dictionary<string, string>(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)
{

stringBuilder.Append(((string)row[colname]));

}

if (uniquenessDict.ContainsKey(stringBuilder.ToString()))
{

rows.Remove(row);

}

else
{

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

rowIndex++;

}

}

}

 



     

Further Readings:

Responses
Author: Andy         Company URL: http://www.dotnetspark.com
Posted Date: January 25, 2011

This was really useful. Thank!!
One improvement can be made to increase the robustness:

stringBuilder.Append(((string)row[colname]));

should be replaced with:

stringBuilder.Append(row[colname].ToString());

The ToString() method will cast anything to a string, whereas the (string) cast throws errors depending on the type of value in the cell




Post Comment

You must Sign In To post reply
Find More code samples in C#, ASP.Net, Vb.Net and more Here

Hall of Fame    Twitter   Terms of Service    Privacy Policy    Contact Us    Archives   Tell A Friend