Is it possible to count all the items that satisfy predicate and the ones that don't in one iteration over the table?

huangapple go评论99阅读模式
英文:

Is it possible to count all the items that satisfy predicate and the ones that don't in one iteration over the table?

问题

我有一个问题:

  1. var x = from c in _context
  2. [...]
  3. group subResult by subResult.Id into g
  4. select new
  5. {
  6. g.Key,
  7. Count1 = g.Where(predicate).Count(),
  8. Count2 = g.Where(!predicate).Count()
  9. }

如果 g.Count()==Count1 + Count2,那么在 Count1Count2 的谓词中是否有可能简化查询,以便不重复计算并且仍然在服务器端进行计数?

编辑:这是我得到的结果

Is it possible to count all the items that satisfy predicate and the ones that don't in one iteration over the table?

英文:

I have a query:

  1. var x = from c in _context
  2. [...]
  3. group subResult by subResult.Id into g
  4. select new
  5. {
  6. g.Key,
  7. Count1 = g.Where(predicate).Count(),
  8. Count2 = g.Where(!predicate).Count()
  9. }

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

Is it possible to count all the items that satisfy predicate and the ones that don't in one iteration over the table?

答案1

得分: 1

这是如何使用Aggregate

  1. var x =
  2. from c in _context
  3. [...]
  4. group subResult by subResult.Id into g
  5. let count = g.Aggregate((t: 0, f: 0), (a, x) => predicate(x) ? (a.t + 1, a.f) : (a.t, a.f + 1))
  6. select new
  7. {
  8. g.Key,
  9. Count1 = count.t,
  10. Count2 = count.f
  11. };

实际上,你想知道g的类型,如果它是一个IPartition<T>,那么CountO(1),然后Aggregate的性能会更差。

英文:

Here's how using Aggregate:

  1. var x =
  2. from c in _context
  3. [...]
  4. group subResult by subResult.Id into g
  5. let count = g.Aggregate((t: 0, f : 0), (a, x) =&gt; predicate(x) ? (a.t + 1, a.f) : (a.t, a.f + 1))
  6. select new
  7. {
  8. g.Key,
  9. Count1 = count.t,
  10. Count2 = count.f
  11. };

You do actually want to know what type g is as if it is a IPartition&lt;T&gt; then Count is O(1) and then Aggregate performs more poorly.

huangapple
  • 本文由 发表于 2023年7月31日 18:21:01
  • 转载请务必保留本文链接:https://go.coder-hub.com/76802668.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定