使用Linq在group子句中获取多个MAX值

时间:2015-08-25 13:58:21

标签: c# linq

我有以下查询:

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

1 个答案:

答案 0 :(得分:2)

我相信这应该有效:

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) }

或者如果你有从汽车到节目设置的导航属性,那么:

var result=CARS.Select(c=>new {
  CARID=c.CARID, 
  agg1=c.Shows.Max(s=>s.WINDOWS), 
  agg2=c.Shows.Max(s=>s.YEAR)});