2013-02-23 61 views
1

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次共i。並且對於每個Max()評估,c2.Length將被發現4次?

回答

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(); 
+0

謝謝。答案缺乏從LinqPad的「Language」下拉列表框中選擇「C#Statement(s)」以便在其中運行的信息。我寧願選擇固定的控制檯應用程序,而不願學習其他工具 – Fulproof 2013-02-23 15:23:47