使用Linq在组子句中获取多个MAX值
本文关键字:MAX 获取 Linq 子句 使用 | 更新日期: 2023-09-27 18:09:48
我有以下查询:
from x in CARS
from y in SHOWS
.Where(y=>y.CARID == x.CARID)
group y.COLOR by x.CARS
into g
select new { CARID = g.Key, WINDOWS = g.Max()}
在linqpad中生成的sql查询是这样的:
SELECT t0.CARID, MAX(t1.WINDOWS) agg1
FROM CARS t0
INNER JOIN SHOWS t1
ON (t1.CARID = t0.CARID)
GROUP BY t0.CARID
如何在Linq中获得另一个最大值,使我的sql看起来像这样:
SELECT t0.CARID, MAX(t1.WINDOWS) agg1, MAX(t1.YEAR) agg2
FROM CARS t0
INNER JOIN SHOWS t1
ON (t1.CARID = t0.CARID)
GROUP BY t0.CARID
我相信这应该能行:
from x in CARS
from y in SHOWS
.Where(y=>y.CARID == x.CARID)
group y by x.CARS into g
select new { CARID = g.Key, agg1 = g.Max(z=>z.WINDOWS), agg2=g.Max(z=>z.YEAR) }
或者如果你设置了从cars到shows的导航属性,那么:
var result=CARS.Select(c=>new {
CARID=c.CARID,
agg1=c.Shows.Max(s=>s.WINDOWS),
agg2=c.Shows.Max(s=>s.YEAR)});