gpt4 book ai didi

c# - linq to sql where子句和计数

转载 作者:太空狗 更新时间:2023-10-30 00:55:51 24 4
gpt4 key购买 nike

我有一个 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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com