【问题标题】:The number of lambda outer subquery iteration variable evaluationslambda 外部子查询迭代变量评估的数量
【发布时间】:2013-02-09 01:29:00
【问题描述】:

来自LINQ QuizQ4和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 次?

【问题讨论】:

    标签: c# linq collections lambda max


    【解决方案1】:

    是的,这是正确的。如果你有 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();
    

    【讨论】:

    • 谢谢。答案缺少从 LinqPad 的“语言”下拉列表框中选择“C# 语句”以便在那里运行它所需的信息。我宁愿坚持使用常规控制台应用程序,也不愿学习其他工具
    猜你喜欢
    • 2013-08-04
    • 2014-07-23
    • 1970-01-01
    • 2013-06-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多