1

LINQ 测验问题和答案到 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 次?

也就是说,对于数组中的每个项目,с将计算一次,即计算将总共进行 4 次。并且对于每次评估会发现 4 次? colorscolors.Max (c2 => c2.Length)Max()Max()c2.Length

4

1 回答 1

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();
于 2013-02-23T13:39:25.363 回答