我非常对LINQ表达式不熟悉并且我正在学习,但我对我遇到的这个障碍感到好奇。其他一切似乎都很简单,但这让我感到非常困惑。 (也许是因为我也是lambda表达的新手)
SELECT * FROM Promotion AS p
INNER JOIN Student AS s ON p.stdId = s.StdID
INNER JOIN CLASS AS c ON p.class_Id = c.CLASS_ID
INNER JOIN BatchMgr AS b ON p.batchId = b.batchId
WHERE p.promotionId
IN( SELECT MAX(promotionId)
FROM Promotion
GROUP BY stdId
);
我试图将其翻译成LINQ,这就是我在
的地方var subquery = ( from promotion in db.promotion.DefaultIfEmpty()
group promotion by new
{
promotionId = promotion.promotionId
}
into gpromotion
select gpromotion.Key.promotionId
);
var res = ( from p in db.promotion.DefaultIfEmpty()
join s in db.students on p.stdId
equals s.StdID into students
join c in db.classes on p.class_Id
equals c.CLASS_ID into classes
join b in db.batchmgr on p.batchId
equals b.BatchId into batchmgr
from b in batchmgr.DefaultIfEmpty()
from c in classes.DefaultIfEmpty()
from s in students.DefaultIfEmpty()
where subquery.Contains(p.promotionId)
select new { s.NAME, s.StdID, p.class_Id, c.CLASSNO, p.promotionId, p.promotedYear, b.BatchId, b.BatchOf, s.ENROLLEDYEAR }
).AsEnumerable();
return Request.CreateResponse(HttpStatusCode.OK, res.ToArray());
正如您从select gpromotion.Key.promotionId
所看到的,我无法弄清楚如何选择最大promotionId
。到目前为止,我发现的所有示例和答案似乎只查询并返回最高promotionId
。我不要那个。对于相同的promotionId
,我需要最高stdId
。
select gpromotion.Key.promotionId.Max(x => x.promoitonId)
但失败了。 小提琴
This是我的代码应该做的(在SQL中)
如您所见,我的要求是删除this等条目并显示only the latest promotionId。
我确定在找到解决方案时我会自己踢,但就目前而言,这真的很麻烦。非常感谢帮助。
答案 0 :(得分:2)
这是相关SQL子查询的LINQ等价物。
方法语法:
var subquery = db.promotion
.GroupBy(p => p.stdId)
.Select(g => g.Max(p => p.promotionId));
查询语法:
var subquery =
from p in db.promotion
group p by p.stdId into g
select g.Max(p => p.promotionId);
带有聚合的非常标准的LINQ group by
查询。您所需要的只是学习如何使用GroupBy
运算符生成的IGrouping<TKey, TElement>
。
答案 1 :(得分:1)
尝试这样的事情:
var res = ( from p in db.promotion
join s in db.students on p.stdId equals s.StdID
join c in db.classes on p.class_Id equals c.CLASS_ID
join b in db.batchmgr on p.batchId equals b.BatchId
let maxPromotionId = (db.promotion.Where(x => x.stdId == s.StdID).Max(m => m.promotionId))
where maxPromotionId == p.promotionId
select new { s.NAME, s.StdID, p.class_Id, c.CLASSNO, p.promotionId, p.promotedYear, b.BatchId, b.BatchOf, s.ENROLLEDYEAR }
).AsEnumerable();