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

后端 未结 11 2143
醉酒成梦
醉酒成梦 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 05:58

    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"
    }
    
    0 讨论(0)
  • 2020-12-13 06:02

    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");
    
    0 讨论(0)
  • 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;
    
    0 讨论(0)
  • 2020-12-13 06:08

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

    0 讨论(0)
  • 2020-12-13 06:09
    foreach(string s in sList)
    {
        if(s.equals("ok"))
        {
                 return true;
        }
    }
    return false;
    
    0 讨论(0)
提交回复
热议问题