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评论68阅读模式
英文:

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,那么在 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:

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

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

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>,那么CountO(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) =&gt; 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&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:

确定