为什么IEnumerable.Count()重新评估查询? [英] Why is IEnumerable.Count() reevaluating the query?
问题描述
当我期望"1 1 1 1"时,以下代码将显示"2 2 2 2".为什么"Count()"会重新评估查询?
The following code prints "2 2 2 2" when I would expect "1 1 1 1". Why does "Count()" reevaluates the query?
class Class1
{
static int GlobalTag = 0;
public Class1()
{
tag = (++GlobalTag);
}
public int tag;
public int calls = 0;
public int Do()
{
calls++;
return tag;
}
}
class Program
{
static void Main(string[] args)
{
Class1[] cls = new Class1[] { new Class1(), new Class1(), new Class1(), new Class1() };
var result = cls.Where(c => (c.Do() % 2) == 0);
if (result.Count() <= 10)
{
if (result.Count() <= 10)
{
foreach (var c in cls)
{
Console.WriteLine(c.calls);
}
}
}
}
}
推荐答案
还可以如何工作?您希望Count()
做什么以缓存值?
How else could it work? What would you expect Count()
to do in order to cache the values?
LINQ to Objects通常会延迟执行,仅在需要时才实际评估查询-例如对元素进行计数.因此,对Where
的调用根本不评估序列;它只是记住谓词和序列,以便它可以在需要时对其进行评估.
LINQ to Objects generally executes lazily, only actually evaluating a query when it needs to - such as to count the elements. So the call to Where
isn't evaluating the sequence at all; it just remembers the predicate and the sequence so that it can evaluate it when it needs to.
有关LINQ to Objects如何工作的更多详细信息,建议您阅读我的 Edulinq博客系列.它相当长(并且还没有完成),但是它将使您对LINQ to Objects的工作原理有更多的了解.
For a lot more details about how LINQ to Objects works, I suggest you read my Edulinq blog series. It's rather long (and not quite finished) but it'll give you a lot more insight into how LINQ to Objects works.
这篇关于为什么IEnumerable.Count()重新评估查询?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!