Remove Duplicate Rows from DataTable in C#
While it is best to get distinct values directly from the SQL statement before entering them into a datatable there is an easy way to remove duplicate rows from datatable in C#.
The following code snippet shows how to remove duplicate rows from datatable in C#.
RemoveDuplicate(ref oInfo); //Call to the method/function
.....
internal static void RemoveDuplicate(ref DataTable oTable){
DataView dv = oTable.DefaultView;
//passing true here will only return distinct records
oTable = dv.ToTable(true);
}
In the code we pass a datatable to the RemoveDuplicate function by reference. Then we create a DataView with values from the DataTable. Once we have the rows in the DataView we can move them back to the DataTable using ToTable(true) which the only moves disinct rows to the DataTable.
You will want to make sure to pass by reference instead of pass by value so that the values are changed on the DataTable. Pass by reference will change the variable at that memory location instead of making a copy of the variable.
Congratulations @randomlyjames! You received a personal award!
You can view your badges on your Steem Board and compare to others on the Steem Ranking
Do not miss the last post from @steemitboard:
Vote for @Steemitboard as a witness to get one more award and increased upvotes!
Downvoting a post can decrease pending rewards and make it less visible. Common reasons:
Submit
Congratulations @randomlyjames! You received a personal award!
You can view your badges on your Steem Board and compare to others on the Steem Ranking
Do not miss the last post from @steemitboard:
Vote for @Steemitboard as a witness to get one more award and increased upvotes!
Downvoting a post can decrease pending rewards and make it less visible. Common reasons:
Submit