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?

Était-ce utile?

La solution

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

Autres conseils

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 
           } 
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top