How do I jump out of a foreach loop in C#?
C#.NetForeachC# Problem Overview
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
}
C# Solutions
Solution 1 - C#
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 - C#
Use break;
and this will exit the foreach loop
Solution 3 - C#
You could avoid explicit loops by taking the LINQ route:
sList.Any(s => s.Equals("ok"))
Solution 4 - C#
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.
Solution 5 - C#
You can use break
which jumps out of the closest enclosing loop, or you can just directly return true
Solution 6 - C#
Use the 'break' statement to escape the loop.
Solution 7 - C#
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 ...
Solution 8 - C#
foreach(string s in sList)
{
if(s.equals("ok"))
{
return true;
}
}
return false;
Solution 9 - C#
Either return straight out of the loop:
foreach(string s in sList){
if(s.equals("ok")){
return true;
}
}
// if you haven't returned by now, no items are "ok"
return false;
Or use break
:
bool isOk = false;
foreach(string s in sList){
if(s.equals("ok")){
isOk = true;
break; // jump out of the loop
}
}
if(isOk)
{
// do something
}
However, in your case it might be better to do something like this:
if(sList.Contains("ok"))
{
// at least one element is "ok"
}
else
{
// no elements are "ok"
}
Solution 10 - C#
It's not a direct answer to your question but there is a much easier way to do what you want. If you are using .NET 3.5 or later, at least. It is called Enumerable.Contains
bool found = sList.Contains("ok");
Solution 11 - C#
var ind=0;
foreach(string s in sList){
if(s.equals("ok")){
return true;
}
ind++;
}
if (ind==sList.length){
return false;
}