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){
var ind=0;
foreach(string s in sList){
if(s.equals("ok")){
return true;
}
ind++;
}
if (ind==sList.length){
return false;
}
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.
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 ...
You could avoid explicit loops by taking the LINQ route:
sList.Any(s => s.Equals("ok"))
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.
Use break;
and this will exit the foreach loop