Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
295 views
Welcome To Ask or Share your Answers For Others

1 Answer

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;

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...