我如何跳过`foreach`循环迭代? [英] How do I skip an iteration of a `foreach` loop?

查看:500
本文介绍了我如何跳过`foreach`循环迭代?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Perl中我可以跳过一个foreach(或任何环路)与迭代旁边; 命令



有没有办法跳过迭代并跳转到下一个循环在C#?

 的foreach(在数量INT号)
{
如果(数字℃下)
{
//善有善报,这里在循环跳跃?
}

//否则进程号
}


解决方案

您想要的:

 的foreach(在数量INT数)//< ---回到这里-------- + 
{// |
如果(数℃,)// |
{// |
继续; //跳过本次迭代的剩余部分。 ----- +
}

//做的工作
}

下面是有关 继续关键字






更新:在回答Brian的后续问题的意见:




你能不能进一步明确,如果我嵌套的循环,我会做什么,要跳过延长子里的一个迭代?

 的for(int []在numberarrays号){
对(在数量INT数){//做什么,如果我想
//跳(数字/ numberarrays)?
}
}




A 继续总是适用于最近的封闭的范围,所以你不能用它打出来的最外层循环。如果这样的情况出现的时候,你需要做一些更复杂的取决于你想要什么,就像从内环,那么继续的外环。看到这里的文档的 关键字 。在 C#关键字是类似于Perl的末页关键字。



此外,考虑达斯汀的建议,只是筛选出的值,你不想来处理事先:

 的foreach(VAR篮子baskets.Where(b = GT; b.IsOpen())){
的foreach(在basket.Where VAR果(F => f.IsTasty())){
cuteAnimal.Eat (水果); //嗡额定标称。你并不需要打破/继续
//因为所有达到这一点的水果是
//可用篮子和美味。
}
}


In Perl I can skip a foreach (or any loop) iteration with a next; command.

Is there a way to skip over an iteration and jump to the next loop in C#?

 foreach (int number in numbers)
 {
     if (number < 0)
     {
         // What goes here to skip over the loop?
     }

     // otherwise process number
 }

解决方案

You want:

foreach (int number in numbers) //   <--- go back to here --------+
{                               //                                |
    if (number < 0)             //                                |
    {                           //                                |
        continue;   // Skip the remainder of this iteration. -----+
    }

    // do work
}

Here's more about the continue keyword.


Update: In response to Brian's follow-up question in the comments:

Could you further clarify what I would do if I had nested for loops, and wanted to skip the iteration of one of the extended ones?

for (int[] numbers in numberarrays) {
  for (int number in numbers) { // What to do if I want to
                                // jump the (numbers/numberarrays)?
  }
}

A continue always applies to the nearest enclosing scope, so you couldn't use it to break out of the outermost loop. If a condition like that arises, you'd need to do something more complicated depending on exactly what you want, like break from the inner loop, then continue on the outer loop. See here for the documentation on the break keyword. The break C# keyword is similar to the Perl last keyword.

Also, consider taking Dustin's suggestion to just filter out values you don't want to process beforehand:

foreach (var basket in baskets.Where(b => b.IsOpen())) {
  foreach (var fruit in basket.Where(f => f.IsTasty())) {
    cuteAnimal.Eat(fruit); // Om nom nom. You don't need to break/continue
                           // since all the fruits that reach this point are
                           // in available baskets and tasty.
  }
}

这篇关于我如何跳过`foreach`循环迭代?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆