11

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.

2
  • the only way is to switch to VB.NEt which allows using thins such as Exit For, Exit Do, Exit While, etc. :)
    – Ry-
    May 21, 2011 at 1:32
  • wow.. i had the same question.. in java you just do "break mylabel;" and you can label any loop. But unlike C#'s 'goto' you can't just put the label anywhere.
    – 00jt
    Jan 31, 2013 at 18:42

3 Answers 3

23

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.
1
  • +1 That was almost exactly my answer but you beat me to it May 21, 2011 at 1:23
8

There's always the dreaded (and much maligned?) goto...

EDIT: After thinking this over for a while it occurs to me that you could use Linq to do this, assuming a few conditions are met.

var query = from item in items
                    from item2 in items2
                     select new { item, item2 };

foreach (var tuple in query)
{
    //...
    break;
}

You can do this more elegantly in F#, though.

1
  • Nice idea with the LINQ bit, since you added that, I'll remove the -1
    – debracey
    May 21, 2011 at 16:47
2

This has been discussed previously in this post:

Breaking out of a nested loop

Short answer: It's really not possible with a single keyword. You'll have to code in some flag logic (as suggested in the answers to the other question.)

I'd personally split it out into separate methods, would putting the loop "block" inside a function and just return (thus breaking both loops) work for you?

1
  • 4
    It's not possible with a single keyword -- unless that keyword is "goto"!
    – phoog
    May 21, 2011 at 4:39

Not the answer you're looking for? Browse other questions tagged or ask your own question.