Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c#

.net

foreach

People also ask

How do you escape a foreach loop?

There is no way to stop or break a forEach() loop other than by throwing an exception. If you need such behaviour, the . forEach() method is the wrong tool, use a plain loop instead. If you are testing the array elements for a predicate and need a boolean return value, you can use every() or some() instead.

How do you exit a foreach loop in C#?

Exit Foreach Loop Using break Keyword In C# Let's say you have a list of colors or an array of colors and you are looping through the list and now you have to exit the foreach loop, you will use the break keyword to exit the loop.

How do I close forEach?

If the EXIT statement has the FOREACH statement as its innermost enclosing statement, the FOREACH keyword must immediately follow the EXIT keyword. The EXIT FOREACH statement unconditionally terminates the FOREACH statement, or else returns an error, if no FOREACH statement encloses the EXIT FOREACH statement.

Does continue break out of foreach loop?

Continue is not the opposite of break , break stops the loop, continue stops the current iteration.


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;

Use break; and this will exit the foreach loop


You could avoid explicit loops by taking the LINQ route:

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

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.


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


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.


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