foreach loop

  • Thread starter Thread starter Mike P
  • Start date Start date
M

Mike P

In a foreach loop, how do you break out of the iteration but not the
loop? Break and continue both seem to exit the loop, I need something
that for example on an if statement will cease execution of the current
iteration and move to the next one.


Any help would be really appreciated.


Cheers,

Mike
 
It works for me

string s = "Hello world";
foreach( char c in s )
{
if( c == 'l' )
continue;
Console.WriteLine(c);
}

This prints out all of the characters except the 'l's. Are you sure you have your continue at the right place in your logic?

Regards

Richard Blewett - DevelopMentor
http://www.dotnetconsult.co.uk/weblog
http://www.dotnetconsult.co.uk

In a foreach loop, how do you break out of the iteration but not the
loop? Break and continue both seem to exit the loop, I need something
that for example on an if statement will cease execution of the current
iteration and move to the next one.


Any help would be really appreciated.
 
In a foreach loop, how do you break out of the iteration but not the
loop? Break and continue both seem to exit the loop, I need something
that for example on an if statement will cease execution of the current
iteration and move to the next one.

Unless you're at the last element within the IEnumerable continue should
iterate to the next element and start from the top of the loop.

foreach (int i in numbers)
{
if (i < 10) continue;
}

In the example above, the loop iterates through all integers in the numbers
array. By using the continue statement in conjunction with the expression (i
< 10), the statements between continue and the end of the for body are
skipped if i is less than ten.

Anders Norås
http://dotnetjunkies.com/weblog/anoras/
 
Doh! I meant break and return not break and continue. I'm guessing
continue is like 'next' for C#?


Thanks,

Mike
 
int [] ints = new int{1,2,3,4,5,6,7,8,9};
foreach(int x in ints)
{
Console.WriteLine(x); // will print all numbers
}

foreach(int x in ints)
{
break;
Console.WriteLine(x); // this row will never run
}

foreach(int x in ints)
{
if(x == 8) break; // will stop execution if 8 is found
Console.WriteLine(x);
}

foreach(int x in ints)
{
if(x % 2 == 0) continue;
Console.WriteLine(x); // will print uneven numbers
}

foreach(int x in ints)
{
if(x = 8) return; // will stop entire method if 8 is found
Console.WriteLine(x);
}

continue means stop executing the body of the for loop and return to
beginning of loop

/mortb
 
Back
Top