Tuesday, January 13, 2015

Get all duplicate values from a Asp.net data table for a particular column.

Here is a method which I have created to get all the rows which have duplicate values for title column. Code is as below :

protected DataTable FormatDataTableForClientDICBIC(DataTable objDatatable)
            DataTable dt = new DataTable();
// Below content in bold format will help us to find all the Title which are present more than once in list with all number of occurences.
            var duplicates = objDatatable.AsEnumerable()
            .Select(dr => dr.Field<string>("Title"))
            .GroupBy(x => x)
            .SelectMany(grp => grp.Skip(1));

            if (duplicates.Count() > 0)
                DataTable dtTitle = new DataTable();
                foreach (var item in duplicates)
                    DataRow dr = dtTitle.NewRow();
                    dr["Title"] = Convert.ToString(item);

// Gets distinct values from each of them.

                DataView view = new DataView(dtTitle);
                DataTable distinctValues = view.ToTable(true, "Title");

                //List<DataRow> rows = new List<DataRow>();
                foreach (DataRow item in distinctValues.Rows)
                    string ICName = Convert.ToString(item["Title"]);
                    //DataRow dr = dt.NewRow();
                    //dr["IC Name"] = ICName;

                    if (!string.IsNullOrEmpty(ICName) && (!(ICName.Equals("TBD") || ICName.Equals(@"N/A") || ICName.Equals("Declined"))))
                        var dataResults = from r in objDatatable.AsEnumerable()
                                          where (Convert.ToString(r["Title"]) == ICName)
                                          select r;
                        if (dataResults.Count() > 0)
                            foreach (var subitems in dataResults)
                                DataRow dr = dt.NewRow();
                                dr["Column1"] = subitems["Column1"];
                                dr["Column2"] = subitems["Column2"];
                                dr["Column3"] = subitems["Column3"];
                                dr["Column4"] = subitems["Column4"];
                                dr["Column5"] = subitems["Column5"];
                                dr[""Column6] = subitems["Column6"];
                                dr["Title"] = subitems["Title"];


            return dt;


Now we can use this returned data table to show all repeated titles with details of all columns. If you want you can also use the schema of Same DataTable which is an input parameter, instead of writing a new one. Hope it helps. Please let me know if there is any better way (performance wise) to do it. 

No comments:

Post a Comment