[英]How do I skip an iteration of a `foreach` loop?
在 Perl 中,我可以使用 next 跳过 foreach(或任何循环)迭代next;
命令。
有没有办法跳过迭代并跳转到 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
关键字的更多信息。
更新:针对布赖恩在评论中的后续问题:
如果我嵌套了 for 循环并想跳过其中一个扩展循环的迭代,您能否进一步澄清我会做什么?
for (int[] numbers in numberarrays) { for (int number in numbers) { // What to do if I want to // jump the (numbers/numberarrays)? } }
continue
始终适用于最近的封闭 scope,因此您不能使用它来跳出最外层的循环。 如果出现这样的情况,你需要根据你想要的做一些更复杂的事情,比如从内部循环中break
,然后在外部循环上continue
。 有关break
关键字的文档,请参见此处。 break
C# 关键字类似于 Perl last
关键字。
另外,考虑采用 Dustin 的建议,只过滤掉您不想事先处理的值:
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.
}
}
另一种方法是在循环执行之前使用 LINQ 进行过滤:
foreach ( int number in numbers.Where(n => n >= 0) )
{
// process number
}
你也可以翻转你的 if 测试:
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
}
如果要跳过多个项目中的第一个。
或者,如果要指定跳过条件,请使用.SkipWhere
。
使用 continue 语句:
foreach(object o 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))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.