解析在內(nèi)部循環(huán)中Continue外部循環(huán)的使用詳解
更新時間:2013年05月14日 10:12:40 作者:
本篇文章是對在內(nèi)部循環(huán)中Continue外部循環(huán)的使用進行了詳細的分析介紹,需要的朋友參考下
有時候你希望在一個嵌套循環(huán)的外層循環(huán)中執(zhí)行Continue操作。例如,假設(shè)你有一連串的標準,和一堆items。
并且你希望找到一個符合每個標準的item。
復制代碼 代碼如下:
match = null;
foreach(var item in items)
{
foreach(var criterion in criteria)
{
if (!criterion.IsMetBy(item)) //如果不符合標準
{
//那么說明這個item肯定不是要查找的,那么應該在外層循環(huán)執(zhí)行continue操作
}
}
match = item;
break;
}
有很多方法可以實現(xiàn)這個需求,這里有一些:
方法#1(丑陋的goto):使用goto語句。
復制代碼 代碼如下:
match = null;
foreach(var item in items)
{
foreach(var criterion in criteria)
{
if (!criterion.IsMetBy(item))
{
goto OUTERCONTINUE;
}
}
match = item;
break;
OUTERCONTINUE:
}
如果不符合其中的一個標準,那么goto OUTCONTINUE:,接著檢查下一個item。
方法#2(優(yōu)雅,漂亮):
當你看到一個嵌套循環(huán),基本上你總是可以考慮將內(nèi)部的循環(huán)放到一個它自己的方法中:
復制代碼 代碼如下:
match = null;
foreach(var item in items)
{
if (MeetsAllCriteria(item, critiera))
{
match = item;
break;
}
}
MeetsAllCriteria方法的內(nèi)部很明顯應該是
復制代碼 代碼如下:
foreach(var criterion in criteria)
if (!criterion.IsMetBy(item))
return false;
return true;
方法#3,使用標志位:
復制代碼 代碼如下:
match = null;
foreach(var item in items)
{
foreach(var criterion in criteria)
{
HasMatch=true;
if (!criterion.IsMetBy(item))
{
// No point in checking anything further; this is not
// a match. We want to “continue” the outer loop. How?
HasMatch=false;
break;
}
}
if(HasMatch) {
match = item;
break;
}
}
方法#4,使用Linq。
復制代碼 代碼如下:
var matches = from item in items
where criteria.All(
criterion=>criterion.IsMetBy(item))
select item;
match = matches.FirstOrDefault();
對于在items中的每個item,都檢查是否滿足所有的標準。
相關(guān)文章
C#中的數(shù)組作為參數(shù)傳遞所引發(fā)的問題
這篇文章主要介紹了C#中的數(shù)組作為參數(shù)傳遞所引發(fā)的問題 的相關(guān)資料,需要的朋友可以參考下2016-03-03
C#使用OpenCvSharp4庫讀取電腦攝像頭數(shù)據(jù)并實時顯示
OpenCvSharp4庫是一個基于.Net封裝的OpenCV庫,本文主要給大家介紹了C#使用OpenCvSharp4庫讀取電腦攝像頭數(shù)據(jù)并實時顯示的詳細方法,感興趣的朋友可以參考下2024-01-01

