Possible Duplicate:
Breaking out开发者_JAVA百科 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.
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.
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.
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?
精彩评论