Unbreakable Unbreakable - 4 years ago 84
Vb.net Question

LINQ query to get the all the datarows based on a distinct column

In VB.Net I have below LINQ Query

Dim temp = (From r In datatable Select r Order By r.str Descending)


But I want it to be unique based on
str
column. I know how to get just the
str column
from the LINQ and mark it as
distinct
. But I want the entire row (all columns) and have the distinct based on
str
column

something like

Dim temp = (From r In datatable Select r Order By r.str Descending).distinct(r.str)


If some one can give me answer in C# I will translate it in VB.Net

Sample

datatable

col1 col2 str
A B X
A1 B1 Y
A2 B2 X


output should be

col1 col2 str
A B X
A1 B1 Y

Answer Source

If you want to select only first row from rows with same str field value:

from r in datatable.AsEnumerable()
group r by r.Field<string>("str") into g
orderby g.Key descending
select g.First()

Or method syntax

datatable.AsEnumerable()
         .GroupBy(r => r.Field<string>("str"))
         .OrderByDescending(g => g.Key)
         .Select(g => g.First())
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download