Exit from nested loops at desired level

Xaqron picture Xaqron · May 21, 2011 · Viewed 20.3k times · Source

Possible Duplicate:
Breaking out of a nested loop

How to exit from nested loops at a specific level. For example:

foreach (item in Items)
{
    foreach (item2 in Items2)
    {
        // Break; => we just exit the inner loop
        //           while we need to break both loops.
    }
}

And if there are more nested loops and we want to exit Nth loop from inside. Something like break(2) at the above example which breaks both loops.

Answer

csano picture csano · May 21, 2011

Two options I can think of:

(1) Set a flag inside the second loop before you break out of it. Follow the inner iteration with a condition that breaks out of the first iteration if the flag is set.

bool flag = false;
foreach (item in Items)
{
    foreach (item2 in Items2)
    {
        flag = true; // whenever you want to break
        break;
    }

    if (flag) break;
}

(2) Use a goto statement.

foreach (item in Items)
{
    foreach (item2 in Items2)
    {
        goto GetMeOutOfHere: // when you want to break out of both
    }

}

GetMeOutOfHere:
// do whatever.