如何离开lambda表达式的身体 [英] How to leave the body of a lambda expression

查看:987
本文介绍了如何离开lambda表达式的身体的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一些名单,我 list.ForEach(L => {...什么...})。现在,在一定条件下我需要停下来遍历列表,但不工作 - 我得到控制不能离开的身体匿名方法或lambda表达式编译错误。

I have some list and I do list.ForEach( l => { ... something ...}). Now, on certain condition I need to stop iterating over the list, but break doesn't work - I get "Control cannot leave the body of an anonymous method or lambda expression" compilation error.

不知道如何克服这个限制?

Any idea how to overcome that restriction?

推荐答案

使用因为拉姆达比for循环不同的方法执行本身不会在这里工作。 A 语句仅用于构建本地的当前功能的突破是有用的。

Using break alone won't work here because the lambda executes in a different method than the for loop. A break statement is only useful for breaking out of constructs local to the current function.

为了支持断点风格离开你需要添加的ForEach ,其中代理可过载通过返回值,循环执行要打破规定。例如:

In order to support a break style leave you'd need to add an overload of ForEach where the delegate can specify via a return value that loop execution should break. For example

public static void ForEach<T>(this IEnumerable<T> enumerable, Func<T, bool> func) {
  foreach (var cur in enumerable) {
    if (!func(cur)) {
      break;
    }
  }
}



现在的这种消费的ForEach 方法可以通过返回从所提供的指定回调

Now a consumer of this ForEach method can specify a break by returning false from the provided callback

myCollection.ForEach(current => {
  if (someCondition) {
    // Need to break
    return false;
  }
  // Keep going
  return true;
}

这篇关于如何离开lambda表达式的身体的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆