ChatGPT解决这个技术问题 Extra ChatGPT

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

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
 }
Notifying the user with their bad input is as important as skipping it!

C
Community

You want:

foreach (int number in numbers) //   <--- go back to here --------+
{                               //                                |
    if (number < 0)             //                                |
    {                           //                                |
        continue;   // Skip the remainder of this iteration. -----+
    }

    // do work
}

Here's more about the continue keyword.

Update: In response to Brian's follow-up question in the comments:

Could you further clarify what I would do if I had nested for loops, and wanted to skip the iteration of one of the extended ones? for (int[] numbers in numberarrays) { for (int number in numbers) { // What to do if I want to // jump the (numbers/numberarrays)? } }

A continue always applies to the nearest enclosing scope, so you couldn't use it to break out of the outermost loop. If a condition like that arises, you'd need to do something more complicated depending on exactly what you want, like break from the inner loop, then continue on the outer loop. See here for the documentation on the break keyword. The break C# keyword is similar to the Perl last keyword.

Also, consider taking Dustin's suggestion to just filter out values you don't want to process beforehand:

foreach (var basket in baskets.Where(b => b.IsOpen())) {
  foreach (var fruit in basket.Where(f => f.IsTasty())) {
    cuteAnimal.Eat(fruit); // Om nom nom. You don't need to break/continue
                           // since all the fruits that reach this point are
                           // in available baskets and tasty.
  }
}

Could you further clarify what I would do if I had nested for loops, and wanted to skip the iteration of one of the extended ones? ex: for (int[] numbers in numberarrays) { for (int number in numbers) { //What to do if want to jump the (numbers/numberarrays) } }
C#'s goto is actually useful for the situation @Brian is asking about. Add a label such as nextArray: at the bottom of the outer loop, and then goto nextArray; when you want to skip to it.
D
Dustin Campbell

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

foreach ( int number in numbers.Where(n => n >= 0) )
{
    // process number
}

+1. Although it's not a direct response to the question, in practice I'd probably prefer this solution to the one I proposed. Using LINQ seems like a good general use case for filtering out loop values you don't want to process.
Is this just tidier or will it actually be quicker in that there is less to foreach? I'm guessing that LINQ is greatly optimized but the LINQ section will have to foreach at some point so theoretically if the dataset is large and the resulting 'filtered' subset is nearly as large, then this will be slower as a foreach has to happen twice? So maybe it depends on expected resultant sub-dataset?
c
crashmstr

You could also flip your if test:


foreach ( int number in numbers )
{
     if ( number >= 0 )
     {
        //process number
     }
 }

:) Thanks! I come up with a basic example because there were some criteria in the beginning of the loop that wouldn't need to be processed, and others that were errors that needed to be caught.
The one LINQ based answer is nice and has an elegance to it, but using an if statement is not wrong.
T
Tamas Czinege
foreach ( int number in numbers )
{
    if ( number < 0 )
    {
        continue;
    }

    //otherwise process number
}

K
Kev

You can use the continue statement.

For example:

foreach(int number in numbers)
{
    if(number < 0)
    {
        continue;
    }
}

A
AlexB

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.


This is the simplest (though maybe the logic inside is the same) way of doing this - now that you have Linq available. Though you should ensure that .Skip is called only once for performance reasons. (Yeah, I see now that this is not the straight forward answer to OP's question, though a valuable addition to this list of answers). +1
This is not relevant to the question. It will skip the first n elements, not elements that are lower than 0.
M
Millicent Achieng

Use the continue statement:

foreach(object number in mycollection) {
     if( number < 0 ) {
         continue;
     }
  }

Don't understand why it is upvoted, this is wrong since he loop over "o", not "number"
Agreed, maybe this is a copy/paste from previous answers? Conceptually valuable as it's a foreach, but please ensure the variables are consistent.
A
AS Mackay

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))

How is this relevant to the question? All you are doing is skipping the first (or the first five elements), regardless of any other criteria. The OP wanted to know how he could skip an iteration (any) and continue with the next one.