177

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
}
2
  • 2
    Funny. In Python you'd simply do return "ok" in sList: - isn't there something comparable in C#? Jun 28, 2011 at 16:39
  • 11
    @Tim Pietzcker: Of course there is, see spender's answer. In fact, after getting used to Linq, a lot of imperative code looks like cave drawings.
    – Roman
    Jun 28, 2011 at 16:40

12 Answers 12

313
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;
1
  • 8
    I would suggest the second example would be better rewritten to bool found = callFunctionInFirstCodeSnipper(list); // do stuff
    – ICR
    Jun 28, 2011 at 17:01
117

Use break; and this will exit the foreach loop

0
61

You could avoid explicit loops by taking the LINQ route:

sList.Any(s => s.Equals("ok"))
2
  • 24
    or just use Contains("ok"). Jun 28, 2011 at 16:43
  • 12
    @Graham Clark: Contains assumes you're iterating over an ICollection<T>. Any would work on anything that of type IEnumerable<T>, and in this case question doesn't explicitly indicate what kind of collection it's iterating over (a List is a pretty fair guess though).
    – Roman
    Jun 28, 2011 at 16:46
37
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.

10

Use the 'break' statement to escape the loop.

0
7

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

3

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

1
foreach(string s in sList)
{
    if(s.equals("ok"))
    {
             return true;
    }
}
return false;
1

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"
}
1

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");
-2

this is an old question but just thought I would add this answer

you could also use a While loop like this

string sample = "";
while(sample == "")
{
    foreach(DataRow row in DataTable.Rows
        sample = row["somecolumn"].ToString();
}

once the string 'sample' no longer = "" the loop will end

6
  • Perhaps code that would compile would help illustrate what you're suggesting? Nov 2, 2022 at 4:22
  • Well? I just tried to put this into action and there was more overhead than I had expected. The use of the 'break;' statement would be a better way to go. Nov 2, 2022 at 5:07
  • You do understand that this code still doesn't compile? Nov 2, 2022 at 6:04
  • Why are you introducing DataRow row in DataTable.Rows when the original question didn't have that at all? Nov 3, 2022 at 4:02
  • The original question was how to exit a foreach loop, and I was just trying to offer a method of exiting a loop using while. I would just ignore my answer and use the answer from Francis Gilbert or mbillard or the one from Cody. Thanks for the criticism Enigmativity. Nov 4, 2022 at 13:17
-3
var ind=0;
foreach(string s in sList){
    if(s.equals("ok")){
        return true;
    }
    ind++;
}
if (ind==sList.length){
    return false;
}
3
  • Pretty sure $ isn't valid C# syntax.
    – Roman
    Jun 28, 2011 at 16:42
  • probably not, im a javascript/php guy. but there is enough code here to apply a working solution... i removed the $ and added var.. probably still not c+ Jun 28, 2011 at 16:46
  • actually var is a perfectly valid C# keyword, so you're good
    – Roman
    Jun 28, 2011 at 16:50

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.