Remove Duplicate Rows from DataTables in C#

in #technology6 years ago (edited)

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#.

image

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.

sep

Crossfit Open 18.3 results
Java Chat Example

Sort:  

Congratulations @randomlyjames! You received a personal award!

Happy Birthday! - You are on the Steem blockchain for 1 year!

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:

Are you a DrugWars early adopter? Benvenuto in famiglia!
Vote for @Steemitboard as a witness to get one more award and increased upvotes!

Congratulations @randomlyjames! You received a personal award!

Happy Steem Birthday! - You are on the Steem blockchain for 2 years!

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:

Downvote challenge - Add up to 3 funny badges to your board
Vote for @Steemitboard as a witness to get one more award and increased upvotes!