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?

有帮助吗?

解决方案

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

其他提示

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 
           } 
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top