我有一个 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();
我在先过滤然后根据初始 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()
SQL Server 将优化掉不需要的分组。最好记录下你为什么这样写。
编辑:我在 int? 中添加了一个看起来很奇怪的类型转换。这样做的原因是告诉 Linq to SQL 假设该值可以为空,并使用 COALELCE 函数调用将 NULL 转换为 0。这也是一个应该记录在案的 hack。
关于c# - linq to sql where子句和计数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9201810/