欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

解析在內(nèi)部循環(huán)中Continue外部循環(huán)的使用詳解

 更新時(shí)間:2013年05月14日 10:12:40   作者:  
本篇文章是對(duì)在內(nèi)部循環(huán)中Continue外部循環(huán)的使用進(jìn)行了詳細(xì)的分析介紹,需要的朋友參考下

有時(shí)候你希望在一個(gè)嵌套循環(huán)的外層循環(huán)中執(zhí)行Continue操作。例如,假設(shè)你有一連串的標(biāo)準(zhǔn),和一堆items。

并且你希望找到一個(gè)符合每個(gè)標(biāo)準(zhǔn)的item。

復(fù)制代碼 代碼如下:

match = null;
foreach(var item in items)
{
  foreach(var criterion in criteria)
  {
    if (!criterion.IsMetBy(item)) //如果不符合標(biāo)準(zhǔn)
    {
        //那么說(shuō)明這個(gè)item肯定不是要查找的,那么應(yīng)該在外層循環(huán)執(zhí)行continue操作
    }
  }
  match = item;
  break;
}

有很多方法可以實(shí)現(xiàn)這個(gè)需求,這里有一些:

方法#1(丑陋的goto):使用goto語(yǔ)句。

復(fù)制代碼 代碼如下:

match = null;
foreach(var item in items)
{
  foreach(var criterion in criteria)
  {
    if (!criterion.IsMetBy(item))
    {
      goto OUTERCONTINUE;
    }
  }
  match = item;
  break;

OUTERCONTINUE:

}


如果不符合其中的一個(gè)標(biāo)準(zhǔn),那么goto OUTCONTINUE:,接著檢查下一個(gè)item。

方法#2(優(yōu)雅,漂亮):

當(dāng)你看到一個(gè)嵌套循環(huán),基本上你總是可以考慮將內(nèi)部的循環(huán)放到一個(gè)它自己的方法中:

復(fù)制代碼 代碼如下:

match = null;
foreach(var item in items)
{
  if (MeetsAllCriteria(item, critiera))
  {
    match = item;
    break;
  }
}

MeetsAllCriteria方法的內(nèi)部很明顯應(yīng)該是
復(fù)制代碼 代碼如下:

foreach(var criterion in criteria)
  if (!criterion.IsMetBy(item))
    return false;
return true;

方法#3,使用標(biāo)志位:
復(fù)制代碼 代碼如下:

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。
復(fù)制代碼 代碼如下:

var matches = from item in items
              where criteria.All(
                criterion=>criterion.IsMetBy(item))
              select item;
match = matches.FirstOrDefault();

對(duì)于在items中的每個(gè)item,都檢查是否滿足所有的標(biāo)準(zhǔn)。

相關(guān)文章

最新評(píng)論