How do I skip an iteration of a `foreach` loop?
在Perl中,我可以使用
有没有一种方法可以跳过一个迭代并跳到C中的下一个循环?
1 2 3 4 5 6 7 8 9 | foreach (int number in numbers) { if (number < 0) { // What goes here to skip over the loop? } // otherwise process number } |
你想要:
1 2 3 4 5 6 7 8 9 | foreach (int number in numbers) // <--- go back to here --------+ { // | if (number < 0) // | { // | continue; // Skip the remainder of this iteration. -----+ } // do work } |
下面是关于
更新:回应布莱恩在评论中的后续问题:
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?
1
2
3
4
5 for (int[] numbers in numberarrays) {
for (int number in numbers) { // What to do if I want to
// jump the (numbers/numberarrays)?
}
}
另外,考虑采纳达斯汀的建议,过滤掉你不想预先处理的值:
1 2 3 4 5 6 7 | 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进行过滤:
1 2 3 4 | foreach ( int number in numbers.Where(n => n >= 0) ) { // process number } |
您还可以翻转if测试:
1 2 3 4 5 6 7 | foreach ( int number in numbers ) { if ( number >= 0 ) { //process number } } |
1 2 3 4 5 6 7 8 9 | foreach ( int number in numbers ) { if ( number < 0 ) { continue; } //otherwise process number } |
使用LINQ的另一种方法是:
1 2 3 4 | foreach ( int number in numbers.Skip(1)) { // process number } |
如果要跳过多个项目中的第一个。
如果要指定跳过条件,请使用
您可以使用
例如:
1 2 3 4 5 6 7 | foreach(int number in numbers) { if(number < 0) { continue; } } |
使用Continue语句:
1 2 3 4 5 | foreach(object o in mycollection) { if( number < 0 ) { continue; } } |