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

后端 未结 11 2169
醉酒成梦
醉酒成梦 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:46

    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.

提交回复
热议问题