user2489853
user2489853

Reputation:

DataTable distinct rows

I have a datatable with duplicate rows.

DataTable dt = new DataTable();
dt.Columns.Add(new DataColumn() { ColumnName = "Id" });
dt.Columns.Add(new DataColumn() { ColumnName = "Name" });
DataRow datarow1 = dt.NewRow();
datarow1["Id"] = 1;
datarow1["Name"] = "George";
dt.Rows.Add(datarow1);
DataRow datarow2 = dt.NewRow();
datarow2["Id"] = 1;
datarow2["Name"] = "George";
dt.Rows.Add(datarow2);
DataRow datarow3 = dt.NewRow();
datarow3["Id"] = 3;
datarow3["Name"] = "David";
dt.Rows.Add(datarow3);

How to extract distinct rows from DataTable?

Upvotes: 0

Views: 4232

Answers (2)

RollemIra
RollemIra

Reputation: 122

I wrote a blog post a long while ago about this very same problem. I used LINQ and IEqualityComparer to solve this problem.

http://www.iramellor.com/LINQ-Distinct-a-DataTable-and-the-IEqualityComparerT

Update

Sorry I just saw the comment below. The URL above isn't working due to a site move. Here is the updated link:

https://iramellor.com/2008/08/26/LINQ-Distinct-a-DataTable-and-the-IEqualityComparer/

Upvotes: 0

user2488066
user2488066

Reputation:

DataTable getDistinctRows = dt.DefaultView.ToTable(true, new string[] { "Id", "Name" });

Upvotes: 2

Related Questions