Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ForEach() : Why can't use break/continue inside

Tags:

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"

like image 726
Rami Alshareef Avatar asked Dec 14 '10 12:12

Rami Alshareef


People also ask

Can I use continue inside forEach?

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.

Can we use break in forEach?

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.

Can we use continue and break statements with the forEach loop?

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.


1 Answers

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.

like image 51
Femaref Avatar answered Oct 10 '22 08:10

Femaref