How to get first record in each group using Linq

Arian picture Arian · Sep 25, 2013 · Viewed 103k times · Source

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 can I do this using linq?

Answer

King King picture King King · Sep 25, 2013
var result = input.GroupBy(x=>x.F1,(key,g)=>g.OrderBy(e=>e.F2).First());