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?
You cannot continue an outer loop from an inner one. You have two options:
The bad one: set a boolean flag before breaking the inner loop, then check this flag and continue if it is set.
The good one: simply refactor your big spagetti code into a set of functions so you do not have inner loops.
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
}
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