25 Feb 2012

Remove duplicate rows from datatable based on column

public static DataTable Dedup(this DataTable tblIn, string KeyColName)
        {
            DataTable tblOut = tblIn.Clone();
            foreach (DataRow row in tblIn.Rows)
            {
                bool found = false;
                string caseIDToTest = row[KeyColName].ToString();
                foreach (DataRow row2 in tblOut.Rows)
                {
                    if (row2[KeyColName].ToString() == caseIDToTest)
                    {
                        found = true;
                        break;
                    }
                }
                if (!found)
                    tblOut.ImportRow(row);
            }
            return tblOut;
        }

No comments:

Post a Comment