繁体   English   中英

linq to sql where子句和计数

[英]linq to sql where clause and counting

我有一个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 SQL假设该值可以为空并使用COALELCE函数调用将NULL转换为0.这也是一个应该记录的hack。

由于您实际上只是在寻找一个结果,这可能是最简单的方法:

var filteredResults = from ....
                      where ....
                      select ....;
var myModel = new MyModel{ Total = filteredResults.Count(), ... };

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM