1

I have a datatable with some data in it... The data is shown below.

____________________________________________________
|    |                    |            |           |
|mid |    usrnme          |   pname    |   prate   |
|---------------------------------------------------
|11  | demo1@gmail.com    |   sample1  |    2000   |
|14  | demo2@live.com     |   sample2  |    5000   |
|15  | demo3@yahoo.com    |   sample3  |    8000   |
|11  | demo1@gmail.com    |   sample1  |    2000   |
|18  | demo4@gmail.com    |   sample4  |    3000   |
====================================================

As you can see the there are two rows with same values in the datatable. So In my code, I need to check whether there is any duplicate rows in my datatable. If there is any duplicate rows, eliminate that particular row, and then move the next row to the eliminated row. In this case, row 1 and row 4 are same, so it has to be corrected. So row 4 has to be deleted and row 5 has to be inserted in 4 th row position. In this way if there are n rows, the n rows has to be checked and corrected like this way. How can this be acheived in c#.net. I'm new to world of c#. Any help from anyone will be a great help for me.. Thanks in advance.

Soner Gönül
  • 97,193
  • 102
  • 206
  • 364
njnjnj
  • 978
  • 4
  • 23
  • 58
  • possible duplicate of [Best way to remove duplicate entries from a data table](http://stackoverflow.com/questions/4415519/best-way-to-remove-duplicate-entries-from-a-data-table) – Soner Gönül Mar 29 '14 at 13:00
  • Are you asking how to remove them from an in memory DataTable object or from a database table? – Steve Mar 29 '14 at 13:04

2 Answers2

1

Use <Datatable>.DefaultView.ToTable(true)

Ex.: dt.DefaultView.ToTable(true);

If we need a column specific distinct rows,use

<Datatable>.DefaultView.ToTable(true,<Columns>)

Ex.: dt.DefaultView.ToTable(true, "EmpId", "Name");

Kalu Singh Rao
  • 1,671
  • 1
  • 16
  • 21
SharK
  • 2,155
  • 1
  • 20
  • 28
0

This is the simplest way to not have duplicate value in your dataTabale. Linq is the best way to achieve this. Please change the dataTable name and datatype of the column as your need. and it should match with the dataTable datatype.

  var avoidDuplicates= from row in ds.Tables["DataTableName"].AsEnumerable()
               group row by row.Field<string>("m_id") into rowGroup
               select new

               {  
                   m_id = rowGroup.Key,

     user_name = string.Join(" ", rowGroup.Select(row => row.Field<string>("usrnme")).Distinct().ToArray()),

     p_name = string.Join(" ", rowGroup.Select(row => row.Field<string>("pname")).Distinct().ToArray()),

                                        prate = string.Join(" ", rowGroup.Select(row => row.Field<decimal>("prate")).Distinct().ToArray()),
    }

I hope this will Solve your issue

Hardik Parmar
  • 1,053
  • 3
  • 15
  • 39