簡體   English   中英

Linq使用本地值推遲執行

[英]Linq deferred execution with local values

我一直在試驗Linq看看它能做些什么 - 到目前為止我真的非常喜歡它:)

我為一個算法寫了一些查詢,但是我沒有得到我預期的結果......枚舉總是返回空:

情況1

List<some_object> next = new List<some_object>();
some_object current = null;

var valid_next_links =
    from candidate in next
    where (current.toTime + TimeSpan.FromMinutes(5) <= candidate.fromTime)
    orderby candidate.fromTime
    select candidate;

current = something;
next = some_list_of_things;

foreach (some_object l in valid_next_links)
{
    //do stuff with l
}

我將查詢聲明更改為內聯,並且工作正常:

案例#2

 foreach (some_object l in
      (from candidate in next
       where (current.toTime + TimeSpan.FromMinutes(5) <= candidate.fromTime)
       orderby candidate.fromTime
       select candidate))
 {
  //do stuff with l
 }

有誰知道為什么它在#1的情況下不起作用? 我理解它的方式,當你聲明它時,查詢沒有被評估,所以我看不出有什么區別。

將捕獲對current更改,但查詢已知道next 將額外項添加到現有列表將使它們顯示在查詢中,但更改變量的值以完全引用其他列表將不會產生任何影響。 基本上,如果您在心理上將查詢從查詢​​表達式擴展為“正常”形式,則lambda表達式中存在的任何變量都將作為變量捕獲,但任何直接作為參數出現的變量都將立即進行求值。 這只會捕獲變量的參考值,而不是列表中的項目,但仍然意味着不會看到更改變量值本身。 您的第一個查詢擴展為:

var valid_next_links = next
      .Where(candidate => (current.toTime + TimeSpan.FromMinutes(5) <= candidate.fromTime))
      .OrderBy(candidate => candidate.fromTime);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM