繁体   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