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?
Using
breakalone won’t work here because the lambda executes in a different method than the for loop. Abreakstatement 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
ForEachwhere the delegate can specify via a return value that loop execution should break. For exampleNow a consumer of this
ForEachmethod can specify abreakby returningfalsefrom the provided callback