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

后端 未结 8 1180
天涯浪人
天涯浪人 2020-12-22 16:09

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#?

相关标签:
8条回答
  • 2020-12-22 16:33

    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))
    
    0 讨论(0)
  • 2020-12-22 16:34

    You can use the continue statement.

    For example:

    foreach(int number in numbers)
    {
        if(number < 0)
        {
            continue;
        }
    }
    
    0 讨论(0)
  • 2020-12-22 16:39

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

    foreach ( int number in numbers.Where(n => n >= 0) )
    {
        // process number
    }
    
    0 讨论(0)
  • 2020-12-22 16:42
    foreach ( int number in numbers )
    {
        if ( number < 0 )
        {
            continue;
        }
    
        //otherwise process number
    }
    
    0 讨论(0)
  • 2020-12-22 16:45

    Use the continue statement:

    foreach(object number in mycollection) {
         if( number < 0 ) {
             continue;
         }
      }
    
    0 讨论(0)
  • 2020-12-22 16:49

    You could also flip your if test:

    
    foreach ( int number in numbers )
    {
         if ( number >= 0 )
         {
            //process number
         }
     }
    
    0 讨论(0)
提交回复
热议问题