C # - foreach loop inside while loop - exit foreach and continue the while loop right away?

while (foo() == true) { foreach (var x in xs) { if (bar(x) == true) { //"break;" out of this foreach //AND "continue;" on the while loop. } } //If I didn't continue, do other stuff. } 

I am a little fixated on how to do this.


Update: I asked a question. I have missed the fact that I need to handle other things if I don't name continue; in a while loop.

Sorry, I didn’t understand that I used the word β€œsomething” twice.

+6
source share
6 answers

If I understand you correctly, you can use LINQ Any / All predicate here:

 while (something) { // You can also write this with the Enumerable.All method if(!xs.Any(x => somePredicate(x)) { // Place code meant for the "If I didn't continue, do other stuff." // block here. } } 
+3
source

I would rewrite this:

 while (foo() == true) { foreach (var x in xs) { if (bar(x) == true) { //"break;" out of this foreach //AND "continue;" on the while loop. } } //If I didn't continue, do other stuff. DoStuff(); } 

a

 while (foo()) // eliminate redundant comparison to "true". { // Eliminate unnecessary loop; the loop is just // for checking to see if any member of xs matches predicate bar, so // just see if any member of xs matches predicate bar! if (!xs.Any(bar)) { DoStuff(); } } 
+14
source
 while (something) { foreach (var x in xs) { if (something is true) { //Break out of this foreach //AND "continue;" on the while loop. break; } } } 
+6
source

This should meet your requirement:

 while (something) { bool doContinue = false; foreach (var x in xs) { if (something is true) { //Break out of this foreach //AND "continue;" on the while loop. doContinue = true; break; } } if (doContinue) continue; // Additional items. } 

This type of code happens often as soon as you need to break for distribution through nested constructs. Whether this is a code smell or not, for discussion :-)

+2
source
 while (something) { foreach (var x in xs) { if (something is true) { break; } } } 

however, not both of these values ​​will always be true ???

0
source

So, do you want to continue working after hacking?

 while (something) { bool hit = false; foreach (var x in xs) { if (something is true) { hit = true; break; } } if(hit) continue; } 
0
source

Source: https://habr.com/ru/post/892844/


All Articles