How to get in LINQ one row for each key

  • A+
Category:Languages

I have list with:

 EMP_ID | UPDATED_DATE | MARK ------ | ------------ | ---- 111    | 01/01/2015   | 99   111    | 01/01/2013   | 85   111    | 01/01/2017   | 80   222    | 01/01/2011   | 70   222    | 01/01/2015   | 55   222    | 01/01/2002   | 60   

I have to select one row for each ID, with the latest UPDATED_DATE, In our etc:

 EMP_ID | UPDATED_DATE | MARK ------ | ------------ | ---- 111    | 01/01/2017   | 80   222    | 01/01/2015   | 55   

This is the code for order:

empMarksList.OrderBy(x=>x.Id).ThenBy(y=>y.UPDATED_DATE) 

 


Use GroupBy:

var items = empMarksList                    .GroupBy(e => e.EMP_ID)                    .Select(grp => grp.OrderByDescending(v => v.UPDATED_DATE).First()); 

Or if you want a Dictionary:

var dict = empMarksList               .GroupBy(e => e.EMP_ID)               .ToDictionary(grp => grp.Key,                             grp => grp.OrderByDescending(v => v.UPDATED_DATE).First()); 

Comment

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: