var result = list.GroupBy(x=>x.EmpId).Select(g=>g.OrderByDescending(y=>y.Id).First());
How to select MAX ID using LINQ?
-
16-06-2023 - |
题
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?
解决方案
其他提示
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
}
不隶属于 StackOverflow