.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 >> Collections >> Post New Resource Bookmark and Share   

 Subscribe to Code Snippets

How to remove duplicate rows from a datatable

Posted By:Syed Shakeer Hussain       Posted Date: August 11, 2009    Points: 10    Category: Collections    URL: http://www.dotnetspark.com  
 

This code Shows How to remove duplicate rows from a datatable

If some rows of a some columns in the datatable are repetitive and duplicate and you want to remove them, then see the example below:

DataColumn[] keyColumns = new DataColumn[] { dtStore.Columns["DocUniqueID"], dtStore.Columns["DocType"] };
//remove the duplicates
RemoveDuplicates(dtStore, keyColumns);

private static void RemoveDuplicates(DataTable tbl,DataColumn[] keyColumns)
{
int rowNdx = 0;
while (rowNdx 0)
{
foreach (DataRow dup in dups)
{
tbl.Rows.Remove(dup);
}
}
else
{
rowNdx++;
}
}
}

private static DataRow[] FindDups(DataTable tbl,int sourceNdx,DataColumn[] keyColumns)
{
ArrayList retVal = new ArrayList();
DataRow sourceRow = tbl.Rows[sourceNdx];
for (int i = sourceNdx + 1; i < tbl.Rows.Count; i++)
{
DataRow targetRow = tbl.Rows[i];
if (IsDup(sourceRow, targetRow, keyColumns))
{
retVal.Add(targetRow);
}
}
return (DataRow[])retVal.ToArray(typeof(DataRow));
}

private static bool IsDup(DataRow sourceRow,DataRow targetRow,DataColumn[] keyColumns)
{
bool retVal = true;
foreach (DataColumn column in keyColumns)
{
retVal = retVal && sourceRow[column].Equals(targetRow[column]);
if (!retVal) break;
}
return retVal;
}


     

Further Readings:

Responses

No response found. Be the first to respond this post

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