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

C#asp.netIf Statement

C# Problem Overview


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

C# Solutions


Solution 1 - C#

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.

Solution 2 - C#

Try this:

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

Solution 3 - C#

You should use:

continue;

Solution 4 - C#

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

Solution 5 - C#

Use continue instead of break. :-)

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionBrendan VogtView Question on Stackoverflow
Solution 1 - C#Steve TownsendView Answer on Stackoverflow
Solution 2 - C#MaxView Answer on Stackoverflow
Solution 3 - C#AamirView Answer on Stackoverflow
Solution 4 - C#Neil KnightView Answer on Stackoverflow
Solution 5 - C#EnigmativityView Answer on Stackoverflow