Alex Rivera | Logout

How do I skip an iteration of a `foreach` loop?

Asked 2009-03-17T12:58:22.377
392

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
 }
Edit
Report

2 Answers

60

Another approach is to filter using LINQ before the loop executes:

foreach ( int number in numbers.Where(n => n >= 0) )
{
    // process number
}
answered 2009-03-17T13:35:19.947
27
foreach ( int number in numbers )
{
    if ( number < 0 )
    {
        continue;
    }

    //otherwise process number
}
answered 2009-03-17T12:59:49.427

Your Answer