英文:
Is it possible to count all the items that satisfy predicate and the ones that don't in one iteration over the table?
问题
我有一个问题:
var x = from c in _context
[...]
group subResult by subResult.Id into g
select new
{
g.Key,
Count1 = g.Where(predicate).Count(),
Count2 = g.Where(!predicate).Count()
}
如果 g.Count()==Count1 + Count2
,那么在 Count1
和 Count2
的谓词中是否有可能简化查询,以便不重复计算并且仍然在服务器端进行计数?
编辑:这是我得到的结果
英文:
I have a query:
var x = from c in _context
[...]
group subResult by subResult.Id into g
select new
{
g.Key,
Count1 = g.Where(predicate).Count(),
Count2 = g.Where(!predicate).Count()
}
Is it possible to simplify query if predicates used for Count1
and Count2
if g.Count()==Count1 + Count2
so counting isn't done twice and still on server-side?
EDIT: This is what I get
答案1
得分: 1
这是如何使用Aggregate
:
var x =
from c in _context
[...]
group subResult by subResult.Id into g
let count = g.Aggregate((t: 0, f: 0), (a, x) => predicate(x) ? (a.t + 1, a.f) : (a.t, a.f + 1))
select new
{
g.Key,
Count1 = count.t,
Count2 = count.f
};
实际上,你想知道g
的类型,如果它是一个IPartition<T>
,那么Count
是O(1)
,然后Aggregate
的性能会更差。
英文:
Here's how using Aggregate
:
var x =
from c in _context
[...]
group subResult by subResult.Id into g
let count = g.Aggregate((t: 0, f : 0), (a, x) => predicate(x) ? (a.t + 1, a.f) : (a.t, a.f + 1))
select new
{
g.Key,
Count1 = count.t,
Count2 = count.f
};
You do actually want to know what type g
is as if it is a IPartition<T>
then Count
is O(1)
and then Aggregate
performs more poorly.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论