lambda外子查询迭代变量计算的数量

时间:2013-02-23 13:19:02

标签: c# linq collections lambda max

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次?

即,对于с数组中的每个项colorscolors.Max (c2 => c2.Length)将被评估一次,即Max()计算将完成4次。对于每次Max()评估,c2.Length将被找到4次?

1 个答案:

答案 0 :(得分: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();