来自LINQ Quiz Q4和Q5的问答
colors
数组定义为:
string[] colors = { "green", "brown", "blue", "red" };
并从 Q4 的答案中查询:
var query =
from c in colors
where c.Length == colors.Max (c2 => c2.Length)
select c;
我是否正确理解外部查询迭代表达式 c2.Length
将被计算 16 次?
也就是说,对于 colors
数组中的每个项目 с
,将评估 colors.Max (c2 => c2.Length)
一次,即 Max()
计算将总共进行 4 次。对于每个 Max()
评估,c2.Length
会被找到 4 次?
最佳答案
是的,没错。如果你有 LINQPad,也很容易检查:
string[] colors = { "green", "brown", "blue", "red" };
int count = 0;
var query =
from c in colors
where c.Length == colors.Max (c2 =>
{
count.Dump();
count++;
return c2.Length;
}
)
select c;
query.Dump();
关于c# - lambda 外部子查询迭代变量评估的次数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15040967/