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

The Solution to How do I jump out of a foreach loop in C#? is


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;

~ Answered on 2011-06-28 16:36:45


Most Viewed Questions: