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#?
foreach (int number in numbers)
{
if (number < 0)
{
// What goes here to skip over the loop?
}
// otherwise process number
}
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))
Use the continue statement:
foreach(object number in mycollection) {
if( number < 0 ) {
continue;
}
}
Another approach using linq is:
foreach ( int number in numbers.Skip(1))
{
// process number
}
If you want to skip the first in a number of items.
Or use .SkipWhere
if you want to specify a condition for skipping.
foreach ( int number in numbers )
{
if ( number < 0 )
{
continue;
}
//otherwise process number
}
You can use the continue
statement.
For example:
foreach(int number in numbers)
{
if(number < 0)
{
continue;
}
}
You could also flip your if test:
foreach ( int number in numbers )
{
if ( number >= 0 )
{
//process number
}
}
Another approach is to filter using LINQ before the loop executes:
foreach ( int number in numbers.Where(n => n >= 0) )
{
// process number
}
Source: Stackoverflow.com