47

What is the best way to remove duplicate entries from a Data Table?

BenMorel
  • 34,448
  • 50
  • 182
  • 322
Ananth
  • 10,330
  • 24
  • 82
  • 109

11 Answers11

108

Do dtEmp on your current working DataTable:

DataTable distinctTable = dtEmp.DefaultView.ToTable( /*distinct*/ true);

It's nice.

Jeroen
  • 60,696
  • 40
  • 206
  • 339
jai
  • 1,081
  • 1
  • 7
  • 2
  • 8
    This answer deserves more attention, was exactly what I needed and way simpler than building a hashtable/dictionary/whatever as long as you only need to filter exact duplicates. – lee Jul 23 '14 at 06:20
  • 1
    Be careful of the performance of this solution. In my implementation ToTable() was quite slow taking 30 times longer than the original query that got the data. – Ed Greaves Jun 02 '15 at 18:17
  • 1
    This is very nice but it can very, very slow for larger data tables. I tried this on a datatable with 800k records with 20 or so columns and it was running for several minutes (I didn't even wait for it to complete) on my 8 vCPU Windows 7 PC. – Igor Pashchuk Sep 24 '19 at 19:48
85

Remove Duplicates

public DataTable RemoveDuplicateRows(DataTable dTable, string colName)
{
   Hashtable hTable = new Hashtable();
   ArrayList duplicateList = new ArrayList();

   //Add list of all the unique item value to hashtable, which stores combination of key, value pair.
   //And add duplicate item value in arraylist.
   foreach (DataRow drow in dTable.Rows)
   {
      if (hTable.Contains(drow[colName]))
         duplicateList.Add(drow);
      else
         hTable.Add(drow[colName], string.Empty); 
   }

   //Removing a list of duplicate items from datatable.
   foreach (DataRow dRow in duplicateList)
      dTable.Rows.Remove(dRow);

   //Datatable which contains unique records will be return as output.
      return dTable;
}

Here Links below

http://www.dotnetspider.com/resources/4535-Remove-duplicate-records-from-table.aspx

http://www.dotnetspark.com/kb/94-remove-duplicate-rows-value-from-datatable.aspx

For remove duplicates in column

http://dotnetguts.blogspot.com/2007/02/removing-duplicate-records-from.html

ratty
  • 13,216
  • 29
  • 75
  • 108
  • :How can I do it for multiple columns.I tried including string[] colName.But Table.Rows.Remove(dRow); throws error like "The given DataRow is not in the current DataRowCollection".Please suggest. – user1495475 Oct 17 '12 at 12:05
  • You would have to modify the foreach incrementally on more levels. However, using Linq might be easier. http://stackoverflow.com/questions/8939516/how-to-find-duplicate-record-using-linq-from-datatable – miracules Apr 18 '13 at 08:50
  • The Link from dotnetspark worked for me, because i needed to remove rows only if 2 column's rows match .This only works for one type however, but it is fine for me!! – DarkPh03n1X Nov 11 '15 at 18:20
  • this solution is based on column. maybe one column is same but others not. – Nastaran Hakimi Jan 25 '17 at 08:13
  • Works a treat, thank you – WiiLF Dec 19 '21 at 02:50
26

A simple way would be:

 var newDt= dt.AsEnumerable()
                 .GroupBy(x => x.Field<int>("ColumnName"))
                 .Select(y => y.First())
                 .CopyToDataTable();
Hasan Shouman
  • 2,162
  • 1
  • 20
  • 26
  • 2
    This is the one for me. Without removing additional columns, simply ignoring duplicate records for the mentioned column names. – Sagar Khatri Jul 06 '20 at 15:19
19

This post is regarding fetching only Distincts rows from Data table on basis of multiple Columns.

Public coid removeDuplicatesRows(DataTable dt)
{
  DataTable uniqueCols = dt.DefaultView.ToTable(true, "RNORFQNo", "ManufacturerPartNo",  "RNORFQId", "ItemId", "RNONo", "Quantity", "NSNNo", "UOMName", "MOQ", "ItemDescription");
} 

You need to call this method and you need to assign value to datatable. In Above code we have RNORFQNo , PartNo,RFQ id,ItemId, RNONo, QUantity, NSNNO, UOMName,MOQ, and Item Description as Column on which we want distinct values.

Taryn
  • 242,637
  • 56
  • 362
  • 405
Kanav SHarma
  • 191
  • 1
  • 2
10

Heres a easy and fast way using AsEnumerable().Distinct()

private DataTable RemoveDuplicatesRecords(DataTable dt)
{
    //Returns just 5 unique rows
    var UniqueRows = dt.AsEnumerable().Distinct(DataRowComparer.Default);
    DataTable dt2 = UniqueRows.CopyToDataTable();
    return dt2;
}
Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
Satinder singh
  • 10,100
  • 16
  • 60
  • 102
3
    /* To eliminate Duplicate rows */
    private void RemoveDuplicates(DataTable dt)
    {

        if (dt.Rows.Count > 0)
        {
            for (int i = dt.Rows.Count - 1; i >= 0; i--)
            {
                if (i == 0)
                {
                    break;
                }
                for (int j = i - 1; j >= 0; j--)
                {
                    if (Convert.ToInt32(dt.Rows[i]["ID"]) == Convert.ToInt32(dt.Rows[j]["ID"]) && dt.Rows[i]["Name"].ToString() == dt.Rows[j]["Name"].ToString())
                    {
                        dt.Rows[i].Delete();
                        break;
                    }
                }
            }
            dt.AcceptChanges();
        }
    }
veman
  • 31
  • 1
3

There is a simple way using Linq GroupBy Method.

var duplicateValues = dt.AsEnumerable() 

        .GroupBy(row => row[0]) 

        .Where(group => (group.Count() == 1 || group.Count() > 1)) 

        .Select(g => g.Key); 



foreach (var d in duplicateValues)

        Console.WriteLine(d);
Tom
  • 31
  • 1
2

Completely distinct rows:

public static DataTable Dictinct(this dt) => dt.DefaultView.ToTable(true);

Distinct by particular row(s) (Note that the columns mentioned in "distinctCulumnNames" will be returned in resulting DataTable):

public static DataTable Dictinct(this dt, params string[] distinctColumnNames) => 
dt.DefaultView.ToTable(true, distinctColumnNames);

Distinct by particular column (preserves all columns in given DataTable):

public static void Distinct(this DataTable dataTable, string distinctColumnName)
{
    var distinctResult = new DataTable();
    distinctResult.Merge(
                     .GroupBy(row => row.Field<object>(distinctColumnName))
                     .Select(group => group.First())
                     .CopyToDataTable()
            );

    if (distinctResult.DefaultView.Count < dataTable.DefaultView.Count)
    {
        dataTable.Clear();
        dataTable.Merge(distinctResult);
        dataTable.AcceptChanges();
    }
}
0

You can use the DefaultView.ToTable method of a DataTable to do the filtering like this (adapt to C#):

 Public Sub RemoveDuplicateRows(ByRef rDataTable As DataTable)
    Dim pNewDataTable As DataTable
    Dim pCurrentRowCopy As DataRow
    Dim pColumnList As New List(Of String)
    Dim pColumn As DataColumn

    'Build column list
    For Each pColumn In rDataTable.Columns
        pColumnList.Add(pColumn.ColumnName)
    Next

    'Filter by all columns
    pNewDataTable = rDataTable.DefaultView.ToTable(True, pColumnList.ToArray)

    rDataTable = rDataTable.Clone

    'Import rows into original table structure
    For Each pCurrentRowCopy In pNewDataTable.Rows
        rDataTable.ImportRow(pCurrentRowCopy)
    Next
End Sub
David Ruiz
  • 383
  • 1
  • 4
  • 10
0

In order to distinct all datatable columns, you can easily retrieve the names of the columns in a string array

public static DataTable RemoveDuplicateRows(this DataTable dataTable)
{
    List<string> columnNames = new List<string>();
    foreach (DataColumn col in dataTable.Columns)
    {
        columnNames.Add(col.ColumnName);
    }
    return dataTable.DefaultView.ToTable(true, columnNames.Select(c => c.ToString()).ToArray());
}

As you can notice, I thought of using it as an extension to DataTable class

0

I would prefer this as this is faster than DefaultView.ToTable and foreach loop to remove duplicates. Using this, we can have group by on multiple columns as well.

DataTable distinctDT = (from rows in dt.AsEnumerable() 
group rows by new { ColA = rows["ColA"], ColB = rows["ColB"]} into grp
select grp.First()).CopyToDataTable();
rwykr
  • 21
  • 4