simple way of continuing out of outter loop

J

Jon Slaughter

Say I have two nested foreach loops, is there any simple way of continuing
out of the outter most loop depending on what happens in the inner most?

e.g.,

foreach(int i in I)
{
foreach(int j in J)
if (j == 3)
break.continue;
}

where break.continue means break out of inner loop and continue in outter
loop.

I doubt such a thing exists but just curious

Thanks,
Jon
 
J

Jon Skeet [C# MVP]

Jon Slaughter said:
Say I have two nested foreach loops, is there any simple way of continuing
out of the outter most loop depending on what happens in the inner most?

e.g.,

foreach(int i in I)
{
foreach(int j in J)
if (j == 3)
break.continue;
}

where break.continue means break out of inner loop and continue in outter
loop.

I doubt such a thing exists but just curious

Well, you *could* use a goto, if you absolutely had to. I'd normally
try to design my way around it though (to allow a return statement to
work, for instance), or set a boolean flag which the outer loop can
notice and break.
 
J

Jon Slaughter

Jon Skeet said:
Well, you *could* use a goto, if you absolutely had to. I'd normally
try to design my way around it though (to allow a return statement to
work, for instance), or set a boolean flag which the outer loop can
notice and break.

Yeah, I was trying to avoid the bool flag. In fact what I did was juse a
function to do the inner loop since it was just a test.

// Checks if types of A is of type Q for each element in the container
private bool ContainsType<A, Q>(IEnumerable list)
{
foreach (A a in list)
if (a is Q)
return true;
return false;
}

So that is for my inner loop. More work than setting a flag but more
general. (the only real issue is if I'm checking more than one type in the
list I'm wasting cycles ;/ Maybe a flag would have been better ;/ (I think
though for my specific situation I'll only have to use the function a few
times at most so maybe the clarity is better)
 
B

Ben Voigt [C++ MVP]

Jon said:
Say I have two nested foreach loops, is there any simple way of
continuing out of the outter most loop depending on what happens in
the inner most?
e.g.,

foreach(int i in I)
{
foreach(int j in J)
if (j == 3)
break.continue;
}

where break.continue means break out of inner loop and continue in
outter loop.

With the code you showed, just "break;" will do exactly that (because the
inner loop is the last statement block in the outer loop body).
 
J

Jon Skeet [C# MVP]

With the code you showed, just "break;" will do exactly that (because the
inner loop is the last statement block in the outer loop body).

Doh! Misread the question, assuming Mr Slaughter wanted to break out
of both. Oops!

Jon
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top