Question

From the sql data below, I'd like to take a distinct EmpId that is the max ID.

ID  EmpId  DeptId
1   1002   XY
5   1100   ABC
6   1109   EF
7   1100   MN
9   1100   DE
10  1250   CE
11  1250   DJ
12  1100   DE

Results would look like the following:

ID  EmpId  DeptId
1   1002   XY
6   1109   EF
11  1250   DJ
12  1100   DE

How should this LINQ be structured?

Was it helpful?

Solution

var result = list.GroupBy(x=>x.EmpId).Select(g=>g.OrderByDescending(y=>y.Id).First());

OTHER TIPS

from e in context.Employees
group e by e.EmpId into g
select new {EmpId = g.Key, 
            ID = g.OrderByDescending(gg=>gg.ID).FirstOrDefault().ID,
            DeptId = g.OrderByDescending(gg=>gg.ID).FirstOrDefault().DeptId 
           } 
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top