Arian Arian - 13 days ago 15
C# Question

How to get first record in each group using Linq

Considering the following records:

Id F1 F2 F3
-------------------------------------------------
1 Nima 1990 10
2 Nima 1990 11
3 Nima 2000 12
4 John 2001 1
5 John 2002 2
6 Sara 2010 4


I want to group by based on the
F1
field and sort by
Id
and get all fields from the first record of group similar to these records:

Id F1 F2 F3
-------------------------------------------------
1 Nima 1990 10
4 John 2001 1
6 Sara 2010 4


How I can do this using linq?

Answer
    var res = from element in list
              group element by element.F1
                  into groups
                  select groups.OrderBy(p => p.F2).First();
Comments