C# Tutorials and offshore development in India
    Tutorials   Resources   Forum   Reviews   Communities   Interview   Jobs   Projects   Training   Your Ad Here    
Silverlight Games | Mentor | Code Converter | Articles | Code Factory | Computer Jokes | Members | Peer Appraisal | IT Companies | Bookmarks | Polls | Revenue Sharing | Lobby | Gift Shop |


Prizes & Awards
My Profile



Active Members
TodayLast 7 Days more...






Resources » Code Snippets » ADO.NET »

Remove duplicate records from a table


Posted Date: 26 Feb 2007    Resource Type: Code Snippets    Category: ADO.NET
Author: DotNetGuts (DNG)Member Level: Diamond    
Rating: 1 out of 5Points: 10



This code sample shows how to identify and remove duplicate records from a dataset/datatable.

Following Code will take inputs datatable and column name wherein we need to find duplicates items and remove.

							
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(drow[colName]))
duplicateList.Add(drow);
else
hTable.Add(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;
}


Example showing how to use above method:


protected void Button1_Click(object sender, EventArgs e)
{
string strConn = ConfigurationManager.ConnectionStrings["ConnectionString"].ToString();
SqlConnection conn = new SqlConnection(strConn);

SqlDataAdapter da = new SqlDataAdapter("select * from emp", conn);
DataSet ds = new DataSet();
da.Fill(ds, "Emp");

// Filling a employee table
DataTable dt = ds.Tables["Emp"];
dt = RemoveDuplicateRows(dt, "empname");

GridView1.DataSource = ds.Tables["Emp"].DefaultView;
GridView1.DataBind();
}



Responses

Author: Varma Suresh    14 Oct 2009Member Level: Gold   Points : 1
hi,It is good ,Is their any pre defined method to do.

thankyou..
.
varma


Feedbacks      
Popular Tags   What are tags ?   Search Tags  
Sign In to add tags.
(No tags found.)

Post Feedback


This is a strictly moderated forum. Only approved messages will appear in the site. Please use 'Spell Check' in Google toolbar before you submit.
You must Sign In to post a response.
Previous Resource: How to filter the datatable
Return to Discussion Resource Index
Post New Resource
Category: ADO.NET


Post resources and earn money!
 



dotNet Slackers

About Us    Contact Us    Privacy Policy    Terms Of Use