Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Break inner foreach loop and continue outer foreach loop

If I have a nested foreach loop how do I do break the inner loop and tell the outer to continue at that point without doing any other code below the inner loop?

foreach(var item in items) {   foreach(var otheritem in otheritems)   {     if (!double.TryParse(otheritem))     {       //break inner loop       //continue outer loop so we never get to DoStuff()     }   }    DoStuff(); } 
like image 520
Jon Avatar asked Nov 17 '11 14:11

Jon


People also ask

How do you break out of inner loop and continue outer loop?

Using break in a nested loop In a nested loop, a break statement only stops the loop it is placed in. Therefore, if a break is placed in the inner loop, the outer loop still continues. However, if the break is placed in the outer loop, all of the looping stops.

How do I break out of nested foreach?

The only way to this directly is with a goto . Another (better) option is to restructure until the problem goes away. For instance by putting the inner code (while + foreach) in a method and use return to get back.

Does continue break out of foreach loop?

In C#, the continue statement is used to skip over the execution part of the loop(do, while, for, or foreach) on a certain condition, after that, it transfers the control to the beginning of the loop.

How do you continue outer loop?

If what you want to do is a continue-to-outer, you could simply define a label at the top of the outer loop and then "goto" that label. If you felt that doing so did not impede the comprehensibility of the code, then that might be the most expedient solution.


1 Answers

How about using a flag?

foreach(var item in items) {   bool flag = false;   foreach(var otheritem in otheritems)   {     if (!double.TryParse(otheritem))     {         flag = true;         break;     }   }   if(flag) continue;    DoStuff(); } 
like image 154
Tudor Avatar answered Oct 11 '22 10:10

Tudor