How do you break out of a foreach loop while within a switch block?
Normally, you use break but if you use a break within a switch block it will just get you out of a switch block and the foreach loop will continue execution:
foreach (var v in myCollection) { switch (v.id) { case 1: if (true) { break; } break; case 2; break } }
What I'm currently doing when I need to break out of the foreach
while within the switch
block is setting a bool
value placed outside of the loop to true and checking the value of this bool every time the foreach
is entered and before entering the switch block. Something like this:
bool exitLoop; foreach (var v in myCollection) { if (exitLoop) break; switch (v.id) { case 1: if (true) { exitLoop = true; break; } break; case 2; break } }
This works but I keep thinking there must be a better way of doing this I am unaware of...
EDIT: Wonder why this was not implemented in .NET the really neat way it works in PHP as mentioned by @jon_darkstar?
$i = 0; while (++$i) { switch ($i) { case 5: echo "At 5<br />\n"; break 1; /* Exit only the switch. */ case 10: echo "At 10; quitting<br />\n"; break 2; /* Exit the switch and the while. */ default: break; } }
There's no C++ construct for breaking out of the loop in this case. Either use a flag to interrupt the loop or (if appropriate) extract your code into a function and use return .
You can use the break statement to end processing of a particular labeled statement within the switch statement. It branches to the end of the switch statement. Without break , the program continues to the next labeled statement, executing the statements until a break or the end of the statement is reached.
Switching loops can be prevented using Spanning Tree Protocol (STP). The purpose of Spanning Tree Protocol is to select the fastest network path if there are redundant links in the network.
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.
Your solution is pretty much the most common option in this case. That being said, I'd put your exit check at the end:
bool exitLoop; foreach (var v in myCollection) { switch (v.id) { case 1: if (true) { exitLoop = true; } break; case 2; break } // This saves an iteration of the foreach... if (exitLoop) break; }
The other main option is to refactor your code, and pull the switch statement and foreach loop out into a separate method. You could then just return
from inside the switch statement.
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