Since ForEach() method loop through all a list members, Why cant use a break/continue clause while i can use them inside a normal foreach loop
lstTemp.ForEach(i=> { if (i == 3) break; //do sth } );
Error:
"No enclosing loop out of which to break or continue"
To continue in a JavaScript forEach loop you can't use the continue statement because you will get an error. Instead you will need to use the return statement in place of the continue statement because it will act in the same way when using a forEach because you pass in a callback into the forEach statement.
There is no way to stop or break a forEach() loop other than by throwing an exception. If you need such behavior, the forEach() method is the wrong tool.
No, it doesn't, because you pass a callback as a return, which is executed as an ordinary function. All forEach does is call a real, actual function you give to it repeatedly, ignore how it exits, then calls it again on the next element.
Because ForEach
is a method and not a regular foreach
loop. The ForEach
method is there for simple tasks, if you need to break or continue just iterate over lstTemp
with a regular foreach
loop.
Usually, ForEach
is implemented like this:
public static ForEach<T>(this IEnumerable<T> input, Action<T> action) { foreach(var i in input) action(i); }
As it is a normal method call, action
doesn't know anything about the enclosing foreach
, thus you can't break.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With