Select Duplicate Values in a Column in a dataset

There is no direct method to obtain the duplicate values in a column in a dataset.

.Net does not have any method to determine the duplicate values in a column of a DataSet. 
The following code snippet selects the duplicate columnvalues in a specified column, and gives back
the column values in an Arraylist. This collection can be modified to any other new collection.
Please Note:
dataset, tablename, "ID" are only examples. You can change it however the need be.

To use declare a Arraylist as follow:

ArrayList duplicates = SelectDuplicates(dataSet.Tables["tablename"].Copy(),"ID");

ArrayList SelectDuplicates(DataTable table, string columnName) { ArrayList Duplicates = new ArrayList();    object LastValue = table.Rows[0][columnName];    for (int iValue = 1; iValue< table.Rows.Count-1 ; iValue++)    {       if (ColumnEqual(LastValue, table.Rows[iValue][columnName]))       {          Duplicates.Add(LastValue);       }       
      LastValue = table.Rows[iValue][columnName];    }    return Duplicates; } private bool ColumnEqual(object A, object B) { // Compares two values to see if they are equal. Also compares DBNULL.Value. // Note: If your DataTable contains object fields, then you must extend this // function to handle them in a meaningful way if you intend to group on them. if ( A == DBNull.Value && B == DBNull.Value ) // both are DBNull.Value return true;

( A == DBNull.Value || B == DBNull.Value ) // only one is DBNull.Value return false; return ( A.Equals(B) ); // value type standard comparison }
By [)ia6l0 iii   Popularity  (2569 Views)