70
votes

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 checking some stuff. If any of these if statements returns a false then I want it to skip that item and go to the next item in the list. All if statements that follow should be ignored. I tried using a break but a break exits the whole foreach statement.

This is what I currently have:

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
   }

   if (item.Weight > 100)
   {
      // Display error message and move to next item in list.  Skip/ignore all validation
      // that follows beneath
   }
}

Thanks

5
@PaulG: Why did you edit my post? - Brendan Vogt
you can see the edit history by clicking on the interval next to 'edited' - in this case it was a simple typo fix. - Steve Townsend
Yeah sorry, Typo and formatted the 'ifs' as code blocks to make it easier to read (imho) - PaulG

5 Answers

145
votes

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.

17
votes

Try this:

foreach (Item item in myItemsList)
{
  if (SkipCondition) continue;
  // More stuff here
}
12
votes

You should use:

continue;
8
votes

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

6
votes

Use continue instead of break. :-)