ExtensionMethod.NET Home of 880 C#, Visual Basic, F# and Javascript extension methods

Dedup

This method will take any DataTable and remove duplicate rows based on any column.

Source

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;
}

Example

DataTable tbl1 = tbl.Dedup("ColName");

or

tbl1 = tbl1.Dedup("ColName");

Author: John D. Sanders

Submitted on: 17 aug. 2011

Language: C#

Type: System.Data.DataTable

Views: 6084