我有一个linq-to-sql查询,我用它来填充一个具有整数作为属性的对象,其功能是保持计数.
查询看起来像这样(现在)
var TheQuery = from.....
where ....
in thefilteredresults
select new MyModel()
{
Total = thefilteredresults.Count(),
TotalTime = (from x in thefilteredresults
where x.Outcome == 4).Sum(t => t)
}.Single();
Run Code Online (Sandbox Code Playgroud)
我先遇到一些问题,然后根据初始where子句的过滤结果进行计数.我需要修改什么?
谢谢.
你可以一起破解这个:
(from x in table
where filter(x)
group x by 0 into g
select new { Count = (int?)g.Count() ?? 0, Sum = (int?)g.Sum(x => x.Value) ?? 0 }).Single()
Run Code Online (Sandbox Code Playgroud)
SQL Server将优化不需要的分组.最好记录为什么你这样写它.
编辑:我包括一个奇怪的演员到int?.这样做的原因是告诉Linq SQL假设该值可以为空并使用COALELCE函数调用将NULL转换为0.这也是一个应该记录的hack.