How do I jump out of a foreach loop in C#?
Solution 1:
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;
Solution 2:
Use break;
and this will exit the foreach loop
Solution 3:
You could avoid explicit loops by taking the LINQ route:
sList.Any(s => s.Equals("ok"))