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

1.6k Views Asked by At

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
2

There are 2 best solutions below

3
Sergey Berezovskiy On BEST ANSWER

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())
1
mike100111 On

First group by the column you want to be distinct, then select the first of each group. This will give you you all the columns for each distinct value in the specified field.

dim results = myDataContext.myTable.GroupBy(Function(f) f.myDistinctField).Select(Function(j) j.FirstOrDefault())