0

我想将此代码转换为 linq:

select t1.title, COUNT(*)as num 
from t1 INNER join t2 on t2.gId = t1.Id 
group by t1.title, t1.cId 
having t1.cId = 2

我尝试了以下代码:

from p in db.t1s join r in db.t2s on p.Id equals r.gId 
where p.cId == 2 
group p by p.title into g 
select new{ name = from o in g select o.title, num = g.Count()}

但这不会正确返回 COUNT。

请指导我如何解决问题

谢谢

4

1 回答 1

0

如果没有样本数据,很难做到正确,但试试这个片段

from p in db.t1s 
join r in db.t2s on p.Id equals r.gId 
where p.cId == 2 
group p by new {p.title, p.cId} into grouped
select new{ name = grouped.Key.title, num = grouped.Count()}

另外,请注意这个 sql:

select t1.title, COUNT(*)as num 
from t1 INNER join t2 on t2.gId = t1.Id 
group by t1.title, t1.cId 
having t1.cId = 2

将始终返回 1 作为 COUNT(*) 的结果。原因是您过滤了 t1.cId = 2 并按 t1.cId 作为第二个参数进行分组。

于 2012-08-15T13:28:54.460 回答