Remove duplicate rows from DataTable with condition - C#

Viewed 926

I have a datatable as below

StudentID  Marks 
 AAA        NULL
 AAA        100
 BBB        200

I have to remove the row from datatable by checking studentID in a condition that

  1. If there are same studentID then remove row with NULL value and display only student id with value.
  2. If both marks are NULL of that student then show only one row.

Resulted Datatable should be

StudentID  Marks 
 AAA        100
 BBB        200

I have tried to remove duplicate rows from above table using below function

     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])&& drow["Marks"]==null)
            {
                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;
    }
1 Answers
DataTable datatabble = new DataTable();
datatabble.Columns.Add("studentid", typeof(string));
datatabble.Columns.Add("marks", typeof(int));

datatabble.Rows.Add("AAA");
datatabble.Rows.Add("AAA",100);
datatabble.Rows.Add("BBB",200);

var duplicates = datatabble.AsEnumerable().GroupBy(r => r[0]).Where(gr => gr.Count() > 1)
            .Select(dupl => dupl.Key).ToList();

var result = datatabble.AsEnumerable().Where(x => 
        (
           (duplicates.Contains(x[0]) && !string.IsNullOrEmpty(x[1].ToString()))
           || !duplicates.Contains(x[0])
        )           
        ).ToList();

Output: You can see output with 2 row count with filtered null value.

enter image description here

Related