How to leave the body of a lambda expression

I have a list and I am doing list.ForEach( l => { ... something ...}) . Now, under a certain condition, I need to stop iterating over the list, but break does not work - I get the error " Control cannot leave the body of an anonymous method or lambda expression ".

Any idea how to overcome this limitation?

+4
source share
3 answers

Using break alone will not work here because lambda is executed in a different method than the for loop. The break statement is only useful for exiting constructs that are local to the current function.

To maintain a stylish break style, you need to add a ForEach overload where the delegate can specify through the return value that should be executed when the loop is executed. for instance

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

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

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

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

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

+6
source

You cannot stop the iteration inside the ForEach lambda, since you do not control the outer loop that the lambda calls. At this point, why don't you use the regular ForEach loop and the break statement - that would be more readable for this case.

+1
source

Source: https://habr.com/ru/post/1393848/


All Articles