Eve
Eve

Reputation: 212

filter a datatable to contain unique columns

I have a datatable as follows

ID(INT NOT NULL AND PK)    Name(NOT NULL NVARCHAR)
1                          Apple
2                          Apple
3                          Apple
4                          Orange
5                          Apple
6                          Orange

I need to filter the datatable such that it contains only unique Names. ID can be any one of the row selected in Table

Required Datatable

ID(INT NOT NULL AND PK)    Name(NOT NULL NVARCHAR)
1/2/3/5(any one)           Apple
4/6(any one)               Orange

Upvotes: 2

Views: 150

Answers (1)

cuongle
cuongle

Reputation: 75306

You can use LINQ to DataTable with GroupBy method:

var result = dt.AsEmumerable()
               .GroupBy(row => row.Field<string>("Name"))
               .Select(g => g.First())
               .CopyToDataTable();

Upvotes: 6

Related Questions