Pages

Thursday, July 11, 2013

Remove the Duplicate Rows from Data Table using LINQ - C#

"dt" is the datatable with the duplicate rows , now we have to remove the duplicate rows 

the field on behalf on which we are removing the duplicate rows is the "Name" field.

var s = dt.AsEnumerable().GroupBy(t => t[0]).Where(t1 => t1.Count() > 1).ToList();


// make new datatable same as the dt, which will contains the unique rows

         DataTable dt_new = dt.Clone();   

// get rows from var "s" and insert into the new datatable "dt_new"

        foreach (var item in s)
        {
            DataRow dr =
dt_new.NewRow();
            dr["Name"] = item.Key.ToString();
           
dt_new.Rows.Add(dr);
        }


"dt_new" is the datatable contains all unique rows acc. to the Name

No comments:

Post a Comment