Posted by

0 Flares Twitter 0 Facebook 0 Google+ 0 StumbleUpon 0 Email -- Filament.io 0 Flares ×

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.

More Info on Passing Parameters