Latest Post

Wednesday, 12 April 2017

How to delete duplicate records from DataTable

I am sharing this article to delete (remove) duplicate records(rows ) from DataTable using C# .

I am populating datatable with duplicate records but later the duplicate records will be removed (deleted).

DataTable dt = new DataTable();
dt.Columns.AddRange(new DataColumn[3]{
                new DataColumn("EmployeeID"),
                new DataColumn("EmployeeName"),
                new DataColumn("Country") });

dt.Rows.Add(1, "Alok Singh", "India");
dt.Rows.Add(1, "Alok Singh", "India");
dt.Rows.Add(2, "Joe Root", "USA");
dt.Rows.Add(2, "Joe Root", "USA");
dt.Rows.Add(3, "Adam Paul", "France");
dt.Rows.Add(3, "Adam Paul", "France");
dt.Rows.Add(3, "Adam Paul", "France");
dt.Rows.Add(4, "Rose Tayor", "Australia");
dt.Rows.Add(4, "Rose Tayor", "Australia");
dt.Rows.Add(4, "Rose Tayor", "Australia");
dt.Rows.Add(4, "Rose Tayor", "Australia");

EmployeeID
EmployeeName
Country
1
Alok Singh
India
1
Alok Singh
India
2
Joe Root
USA
2
Joe Root
USA
3
Adam Paul
France
3
Adam Paul
France
3
Adam Paul
France
4
Rose Tayor
Australia
4
Rose Tayor
Australia
4
Rose Tayor
Australia
4
Rose Tayor
Australia

following is the method that will remove/delete duplicate records


dt = dt.DefaultView.ToTable(true, "EmployeeID", "EmployeeName", "Country");

here we can also pass array string column names like below

string[] ColumnNames = new string[] { "EmployeeID", "EmployeeName", "Country" };
dt = dt.DefaultView.ToTable(true, ColumnNames);

OUTPUT;-

EmployeeID
EmployeeName
Country
1
Alok Singh
India
2
Joe Root
USA
3
Adam Paul
France
4
Rose Tayor
Australia

Government Jobs