Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to leave the body of a lambda expression

Tags:

c#

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?

like image 642
Andrey Avatar asked Jan 30 '12 20:01

Andrey


2 Answers

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.

like image 99
SLaks Avatar answered Sep 20 '22 21:09

SLaks


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.

like image 35
BrokenGlass Avatar answered Sep 19 '22 21:09

BrokenGlass