In Perl I can skip a foreach (or any loop) iteration with a next;
command.
Is there a way to skip over an iteration and jump to the next loop in C#?
The easiest way to do that is like below:
//Skip First Iteration
foreach ( int number in numbers.Skip(1))
//Skip any other like 5th iteration
foreach ( int number in numbers.Skip(5))
You can use the continue statement.
For example:
foreach(int number in numbers)
{
if(number < 0)
{
continue;
}
}
Another approach is to filter using LINQ before the loop executes:
foreach ( int number in numbers.Where(n => n >= 0) )
{
// process number
}
foreach ( int number in numbers )
{
if ( number < 0 )
{
continue;
}
//otherwise process number
}
Use the continue statement:
foreach(object number in mycollection) {
if( number < 0 ) {
continue;
}
}
You could also flip your if test:
foreach ( int number in numbers )
{
if ( number >= 0 )
{
//process number
}
}