在Perl中,我可以通过使用next;
命令跳过foreach(或任何循环)迭代。
在C#中,有没有一种方法可以跳过一个迭代并跳到下一个循环?
foreach (int number in numbers)
{
if (number < 0)
{
// What goes here to skip over the loop?
}
// otherwise process number
}
您需要:
foreach (int number in numbers) // <--- go back to here --------+
{ // |
if (number < 0) // |
{ // |
continue; // Skip the remainder of this iteration. -----+
}
// do work
}
这里更多关于continue
关键字的信息,请参阅continue
关键字。
更新:针对布莱恩在评论中的后续问题,以下是解答:
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)? } }
continue
语句总是应用于最近的封闭作用域,因此您无法使用它来跳出最外层循环。如果出现这样的情况,您需要根据确切需求执行更复杂的操作,例如从内部循环中break
,然后在外部循环中执行continue
。有关break
关键字的文档,请参见此处。C#的break
关键字类似于Perl的last
关键字。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.
}
}
goto
在Brian所询问的情况下实际上非常有用。在外部循环的底部添加一个标签,例如nextArray:
,然后当您想要跳转到它时,使用goto nextArray;
。 - Jacob Krall另一种方法是在循环执行之前使用 LINQ 进行过滤:
foreach ( int number in numbers.Where(n => n >= 0) )
{
// process number
}
foreach ( int number in numbers )
{
if ( number >= 0 )
{
//process number
}
}
foreach ( int number in numbers )
{
if ( number < 0 )
{
continue;
}
//otherwise process number
}
使用 LINQ 的另一种方法是:
foreach ( int number in numbers.Skip(1))
{
// process number
}
如果你想跳过一系列项目中的第一个,请使用`.Skip(1)`。使用 continue 语句:
foreach(object number in mycollection) {
if( number < 0 ) {
continue;
}
}
最简单的方法就是像下面这样:
//Skip First Iteration
foreach ( int number in numbers.Skip(1))
//Skip any other like 5th iteration
foreach ( int number in numbers.Skip(5))