Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove duplicate column values from a datatable without using LINQ

Consider my datatable,

Id  Name  MobNo
1   ac    9566643707
2   bc    9944556612
3   cc    9566643707

How to remove the row 3 which contains duplicate MobNo column value in c# without using LINQ. I have seen similar questions on SO but all the answers uses LINQ.

like image 711
ACP Avatar asked Aug 24 '26 11:08

ACP


2 Answers

The following method did what i want....

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;
    }
like image 144
ACP Avatar answered Aug 27 '26 02:08

ACP


As you are reading your CSV file ( a bit of pseudo code, but you get the picture ):

List<String> uniqueMobiles = new List<String>();

String[] fileLines = readYourFile();

for (String line in fileLines) {
   DataRow row = parseLine(line);
   if (uniqueMobiles.Contains(row["MobNum"])
   {
       continue;
   }
   uniqueMobiles.Add(row["MobNum"]);
   yourDataTable.Rows.Add(row);       
}

This will only load the records with unique mobiles into your data table.

like image 41
Strelok Avatar answered Aug 27 '26 00:08

Strelok



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!