Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/linq/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
linq中的GROUP BY和Have_Linq_Count_Group By_Having - Fatal编程技术网

linq中的GROUP BY和Have

linq中的GROUP BY和Have,linq,count,group-by,having,Linq,Count,Group By,Having,我想将此代码转换为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 sele

我想将此代码转换为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

请指导我如何解决这个问题


谢谢

如果没有示例数据,很难正确获取,但请尝试此片段

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作为计数(*)的结果。原因是您将筛选t1.cId=2并按t1.cId分组作为第二个参数。

请给出一些示例数据、预期结果和实际结果。而且,这肯定不是您的实际代码,因为它将是
Count
而不是
Count
。我们不知道还有什么不准确……在第二次查询中,您按
title
分组,这显然不同于按
title、cId
分组。而
having
子句旨在查询sum或count等聚合值,但您使用
having t1.cId=2
。这应该在
where
子句中完成(顺便说一下,就像您的linq查询一样)。谢谢。如果数据源中没有所有问题,那么很难构建linq。固定的。