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(); }
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.
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.
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.
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.
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(); }
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