Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to break nested foreach loop then go to parent foreach loop on c#

Tags:

I have the following code:

foreach(// Some condition here) {     while (// Some condition here)     {         foreach (// Some condition here)         {              if (// Condition again)              {                   //Do some code              }              if (// Condition again)              {                  //Stop the first foreach then go back to first foreach              }         }     } } 

What I want to do is when I hit the 2nd if statement on the last foreach loop is to return on the first foreach loop.

Note: If the 2nd if statement is not true, it should continue the last foreach loop until the condition is not true.

Thanks in advance!

like image 841
Gerald Avatar asked Jul 11 '13 10:07

Gerald


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 you go to next in foreach?

The reason why using a return statement to continue in a JavaScript forEach loop works is because when you use a forEach loop you have to pass in a callback function. The only way to continue to the next iteration is when your callback function completes and finishes running the code within itself.


2 Answers

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.

like image 73
Henk Holterman Avatar answered Sep 30 '22 18:09

Henk Holterman


Something like this:

resetLoop = false; for(// Some condition here) {     while (// Some condition here)     {         foreach (// Some condition here)         {              if (// Condition again)              {                   //Do some code              }              if (// Condition again)              {                  //Stop the first foreach then go back to first foreach                  resetLoop = true;                  break;              }         }         if (resetLoop) break;     }     if (resetLoop) {         // Reset for loop to beginning         // For example i = 0;     } } 
like image 21
Dusan Avatar answered Sep 30 '22 18:09

Dusan