Home > Dot Net > How to Avoid Duplicate Rows In DataTable

How to Avoid Duplicate Rows In DataTable

April 10th, 2009

Problem

One of the common problems faced in the data retrieval is to avoid duplicate rows from dataset or datatable. If you google for it, you will come across many solutions asking to loop through the complete in order to get rid of the duplicates. There is a very simple solution available in .Net that does not need looping but it comes with one problem that it can apply duplicate on a single column only. 

Solution

For a dataset the following line will return distinct records for the column:

ds.Tables["MyTable"].DefaultView.ToTable(true,”column_name”);

For a datatable the following line of code will return distince records for the column:

dt.DefaultView.ToTable( true, “column_name”);

The first parameter of ToTable is a boolean for distinct or non-distinct. The second one is the name of the column. It is as simple as it looks :)

admin Dot Net , , , , , , ,

  1. May 6th, 2009 at 10:20 | #1

    Hi, interesting post. I have been wondering about this issue,so thanks for posting. I’ll likely be subscribing to your site. Keep up great writing

  2. Qasim Raza
    May 18th, 2009 at 18:25 | #2

    But the problem with this is that it only returns one column for example.
    if you have a table with column
    employee_name, employee_address, employee_department
    and data
    ——————————————————-
    Waseem abc, lahore IT
    Waseem abc, Islamabad Finance

    and you want to get the complete distinct row based on employee name then it will only return employee name in result not the complete row.

    Is there a way to apply distinct filter on dataset or datatable so that we can get complete distinct row

  3. admin
    June 24th, 2009 at 19:31 | #3

    Yeah qasim, that’s why I have mentioned the limitation as well so that reader knows the limitation before proceeding further on the solution.

  4. Parthiban
    December 15th, 2009 at 19:11 | #4

    You can use more than one column too in second parameter like,

    ds.Tables["MyTable"].DefaultView.ToTable(true,”column_name1”,”column_name2”);

    So that u can get the distinct rows with many columns.

  1. No trackbacks yet.

Copyright © 2008-2009 W@rfi