Abdur Rahim
Abdur Rahim

Reputation: 4021

DataTable Select Expression

I want to select those gesellschaft_id's who have duplicates. I used the code below. this is selecting distinct gesellschaft_id. How to write the select expression to select that row, which rows, gesellschaft_id have more values in the datatable?

foreach (DataRow dr1 in table1.Rows)
        {
            DataRow[] drDup = table2.Select("('" + dr1[0].ToString() + "' = gesellschaft_id ) AND Count(gesellschaft_id)>1");

        }

Upvotes: 0

Views: 1033

Answers (3)

Justin Bannister
Justin Bannister

Reputation: 618

You could do something like this, assuming that the first column is the one which you want to check for duplicates. This of course assumes that you have Linq available.

var duplicateIds = table2.AsEnumerable()
                         .GroupBy(row = row[0])
                         .Where(x => x.Count() > 1);

If you add a bit more detail to the question, that would be helpful.

Upvotes: 1

Steve Wilkes
Steve Wilkes

Reputation: 7135

This will give you the DataRows which have a gesellschaft_id which exists in more than one row:

var rowsWithADuplicateGesellschaftId = table1.Rows
    .Cast<DataRow>()
    .GroupBy(row => row["gesellschaft_id"])
    .Where(group => group.Count() > 1)
    .ToArray();

Upvotes: 1

Mennan
Mennan

Reputation: 4497

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

   //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); 
   }

      return duplicateList;
}

Also useful duplicate find and add/remove links:

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

Upvotes: 1

Related Questions