foreach loop

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
 
R

Richard Blewett [DevelopMentor]

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.
 
A

Anders Norås [MCAD]

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/
 
M

Mike P

Doh! I meant break and return not break and continue. I'm guessing
continue is like 'next' for C#?


Thanks,

Mike
 
M

mortb

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
 

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