How to leave the body of a lambda expression

2019-04-09 09:42发布

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?

标签: c# lambda
3条回答
▲ chillily
2楼-- · 2019-04-09 10:06

A lambda expression works just like a method.
It can return whenever you want.

However, List.ForEach does not offer any way to prematurely stop the iteration.
If you need to break, you just use a normal foreach loop.

查看更多
别忘想泡老子
3楼-- · 2019-04-09 10:09

You cannot stop iteration from within a ForEach lambda since you do not have control of the outer loop that is calling the lambda. At that point why don't you use a regular foreach loop and a break statement - that would be much more readable for this case.

查看更多
我命由我不由天
4楼-- · 2019-04-09 10:23

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.

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;
    }
  }
}

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;
}
查看更多
登录 后发表回答