Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Exit from nested loops at desired level [duplicate]

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.

like image 618
Xaqron Avatar asked May 21 '11 01:05

Xaqron


3 Answers

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.
like image 62
csano Avatar answered Nov 16 '22 00:11

csano


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.

like image 26
phoog Avatar answered Nov 15 '22 23:11

phoog


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?

like image 2
debracey Avatar answered Nov 15 '22 23:11

debracey