[c#] How do I jump out of a foreach loop in C#?

How do I break out of a foreach loop in C# if one of the elements meets the requirement?

For example:

foreach(string s in sList){
      if(s.equals("ok")){
       //jump foreach loop and return true
     }
    //no item equals to "ok" then return false
}

This question is related to c# .net foreach

The answer is


You can use break which jumps out of the closest enclosing loop, or you can just directly return true


var ind=0;
foreach(string s in sList){
    if(s.equals("ok")){
        return true;
    }
    ind++;
}
if (ind==sList.length){
    return false;
}

how about:

return(sList.Contains("ok"));

That should do the trick if all you want to do is check for an "ok" and return the answer ...


foreach(string s in sList)
{
    if(s.equals("ok"))
    {
             return true;
    }
}
return false;

It's not a direct answer to your question but there is a much easier way to do what you want. If you are using .NET 3.5 or later, at least. It is called Enumerable.Contains

bool found = sList.Contains("ok");

You could avoid explicit loops by taking the LINQ route:

sList.Any(s => s.Equals("ok"))

Use break; and this will exit the foreach loop


Use the 'break' statement. I find it humorous that the answer to your question is literally in your question! By the way, a simple Google search could have given you the answer.


foreach (var item in listOfItems) {
  if (condition_is_met)
    // Any processing you may need to complete here...
    break; // return true; also works if you're looking to
           // completely exit this function.
}

Should do the trick. The break statement will just end the execution of the loop, while the return statement will obviously terminate the entire function. Judging from your question you may want to use the return true; statement.


Either return straight out of the loop:

foreach(string s in sList){
   if(s.equals("ok")){
      return true;
   }
}

// if you haven't returned by now, no items are "ok"
return false;

Or use break:

bool isOk = false;
foreach(string s in sList){
   if(s.equals("ok")){
      isOk = true;
      break; // jump out of the loop
   }
}

if(isOk)
{
    // do something
}

However, in your case it might be better to do something like this:

if(sList.Contains("ok"))
{
    // at least one element is "ok"
}
else
{
   // no elements are "ok"
}

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 .net

You must add a reference to assembly 'netstandard, Version=2.0.0.0 How to use Bootstrap 4 in ASP.NET Core No authenticationScheme was specified, and there was no DefaultChallengeScheme found with default authentification and custom authorization .net Core 2.0 - Package was restored using .NetFramework 4.6.1 instead of target framework .netCore 2.0. The package may not be fully compatible Update .NET web service to use TLS 1.2 EF Core add-migration Build Failed What is the difference between .NET Core and .NET Standard Class Library project types? Visual Studio 2017 - Could not load file or assembly 'System.Runtime, Version=4.1.0.0' or one of its dependencies Nuget connection attempt failed "Unable to load the service index for source" Token based authentication in Web API without any user interface

Examples related to foreach

Angular ForEach in Angular4/Typescript? How to use forEach in vueJs? Python foreach equivalent Get current index from foreach loop TypeScript for ... of with index / key? JavaScript: Difference between .forEach() and .map() JSON forEach get Key and Value Laravel blade check empty foreach Go to "next" iteration in JavaScript forEach loop Why is "forEach not a function" for this object?