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

后端 未结 11 2201
醉酒成梦
醉酒成梦 2020-12-13 05:40

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){
              


        
11条回答
  •  醉话见心
    2020-12-13 06:05

    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;
    

提交回复
热议问题