如何跳出 C# 中的 foreach 循环? [英] How do I jump out of a foreach loop in C#?
本文介绍了如何跳出 C# 中的 foreach 循环?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如果其中一个元素满足要求,我如何跳出 C# 中的 foreach
循环?
How do I break out of a foreach
loop in C# if one of the elements meets the requirement?
例如:
foreach(string s in sList){
if(s.equals("ok")){
//jump foreach loop and return true
}
//no item equals to "ok" then return false
}
推荐答案
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;
这篇关于如何跳出 C# 中的 foreach 循环?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文