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

Steven Zack picture Steven Zack · Jun 28, 2011 · Viewed 244.7k times · Source

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
}

Answer

mbillard picture mbillard · Jun 28, 2011
foreach (string s in sList)
{
    if (s.equals("ok"))
        return true;
}

return false;

Alternatively, if you need to do some other things after you've found the item:

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

// do stuff

return found;