Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I continue The upper Loop

I have this code:

foreach(int i in Directions)
        {
            if (IsDowner(i))
            {
                while (IsDowner(i))
                {
                    continue;
                    //if (i >= Directions.Count)
                    //{
                    //    break;
                    //}
                }

                //if (i >= Directions.Count)
                //{
                //    break;
                //}

                if (IsForward(i))
                {

                        continue;
                        //if (i >= Directions.Count)
                        //{
                        //    break;
                        //}

                    //check = true;
                }

                //if (i >= Directions.Count)
                //{
                //    break;
                //}

                if (IsUpper(i))
                {
                        //if (i >= Directions.Count)
                        //{
                        //    break;
                        //}
                    num++;
                    //check = false;
                }

                //if (check)
                //{
                //    num++;
                //}
            }
        }

but I want to have continue for foreach in while loop. how can I do this?

like image 782
ahmadali shafiee Avatar asked Dec 01 '22 00:12

ahmadali shafiee


2 Answers

You cannot continue an outer loop from an inner one. You have two options:

  1. The bad one: set a boolean flag before breaking the inner loop, then check this flag and continue if it is set.

  2. The good one: simply refactor your big spagetti code into a set of functions so you do not have inner loops.

like image 168
Alexey Raga Avatar answered Dec 04 '22 11:12

Alexey Raga


You could break out of the while loop and move on to the next iteration of the outer foreach loop which will start a new while loop:

foreach(int i in Directions)
{
    while (IsDowner(i))
    {
        break;
    }
}

If you had some other code after the while loop that you don't want to be executed in this case you could use a boolean variable which will be set before breaking out of the while loop so that this code doesn't execute and automatically jump on the next iteration of the forach loop:

foreach(int i in Directions)
{
    bool broken = false;
    while (IsDowner(i))
    {
        // if some condition =>
        broken = true;
        break;
    }

    if (broken) 
    {
        // we have broken out of the inner while loop
        // and we don't want to execute the code afterwards
        // so we are continuing on the next iteration of the
        // outer foreach loop
        continue;
    }

    // execute some other code
}
like image 30
Darin Dimitrov Avatar answered Dec 04 '22 10:12

Darin Dimitrov