[英]How do I jump out of a foreach loop in C#?
如果其中一個元素滿足要求,我如何打破 C# 中的foreach
循環?
例如:
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;
或者,如果您在找到該項目后需要做一些其他事情:
bool found = false;
foreach (string s in sList)
{
if (s.equals("ok"))
{
found = true;
break; // get out of the loop
}
}
// do stuff
return found;
使用break;
這將退出 foreach 循環
您可以通過采用 LINQ 路線來避免顯式循環:
sList.Any(s => s.Equals("ok"))
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.
}
應該做的伎倆。 break語句只會結束循環的執行,而return語句顯然會終止整個function。 從您的問題來看,您可能希望使用 return true; 陳述。
您可以使用跳出最近的封閉循環的break
,或者您可以直接return true
使用'break'語句。 順便說一句,我覺得你的問題的答案就在你的問題中,這很幽默。 一個簡單的谷歌搜索就能給你答案。
怎么樣:
return(sList.Contains("ok"));
如果您只想檢查“確定”並返回答案,那應該可以解決問題...
這不是您問題的直接答案,但有一種更簡單的方法可以做您想做的事情。 如果您使用的是 .NET 3.5 或更高版本,至少。 它被稱為Enumerable.Contains
bool found = sList.Contains("ok");
foreach(string s in sList)
{
if(s.equals("ok"))
{
return true;
}
}
return false;
要么直接退出循環:
foreach(string s in sList){
if(s.equals("ok")){
return true;
}
}
// if you haven't returned by now, no items are "ok"
return false;
或使用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
}
但是,在您的情況下,最好執行以下操作:
if(sList.Contains("ok"))
{
// at least one element is "ok"
}
else
{
// no elements are "ok"
}
var ind=0;
foreach(string s in sList){
if(s.equals("ok")){
return true;
}
ind++;
}
if (ind==sList.length){
return false;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.