C# go to next item in list based on if statement in foreach

前端 未结 5 2240
深忆病人
深忆病人 2020-12-14 05:42

I am using C#. I have a list of items. I loop through each item using a foreach. Inside my foreach I have a lot of if statements ch

相关标签:
5条回答
  • 2020-12-14 05:47

    Use continue instead of break. :-)

    0 讨论(0)
  • 2020-12-14 05:50

    Try this:

    foreach (Item item in myItemsList)
    {
      if (SkipCondition) continue;
      // More stuff here
    }
    
    0 讨论(0)
  • 2020-12-14 06:04

    The continue keyword will do what you are after. break will exit out of the foreach loop, so you'll want to avoid that.

    0 讨论(0)
  • 2020-12-14 06:06

    Use continue; instead of break; to enter the next iteration of the loop without executing any more of the contained code.

    foreach (Item item in myItemsList)
    {
       if (item.Name == string.Empty)
       {
          // Display error message and move to next item in list.  Skip/ignore all validation
          // that follows beneath
          continue;
       }
    
       if (item.Weight > 100)
       {
          // Display error message and move to next item in list.  Skip/ignore all validation
          // that follows beneath
          continue;
       }
    }
    

    Official docs are here, but they don't add very much color.

    0 讨论(0)
  • 2020-12-14 06:11

    You should use:

    continue;
    
    0 讨论(0)
提交回复
热议问题