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

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

This question is related to c# asp.net if-statement

The answer is


Try this:

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

Use continue instead of break. :-)


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


You should use:

continue;

Examples related to c#

How can I convert this one line of ActionScript to C#? Microsoft Advertising SDK doesn't deliverer ads How to use a global array in C#? How to correctly write async method? C# - insert values from file into two arrays Uploading into folder in FTP? Are these methods thread safe? dotnet ef not found in .NET Core 3 HTTP Error 500.30 - ANCM In-Process Start Failure Best way to "push" into C# array

Examples related to asp.net

RegisterStartupScript from code behind not working when Update Panel is used You must add a reference to assembly 'netstandard, Version=2.0.0.0 No authenticationScheme was specified, and there was no DefaultChallengeScheme found with default authentification and custom authorization How to use log4net in Asp.net core 2.0 Visual Studio 2017 error: Unable to start program, An operation is not legal in the current state How to create roles in ASP.NET Core and assign them to users? How to handle Uncaught (in promise) DOMException: The play() request was interrupted by a call to pause() ASP.NET Core Web API Authentication Could not load file or assembly 'CrystalDecisions.ReportAppServer.CommLayer, Version=13.0.2000.0 WebForms UnobtrusiveValidationMode requires a ScriptResourceMapping for jquery

Examples related to if-statement

How to use *ngIf else? SQL Server IF EXISTS THEN 1 ELSE 2 What is a good practice to check if an environmental variable exists or not? Using OR operator in a jquery if statement R multiple conditions in if statement Syntax for an If statement using a boolean How to have multiple conditions for one if statement in python Ifelse statement in R with multiple conditions If strings starts with in PowerShell Multiple conditions in an IF statement in Excel VBA