2009-05-06 59 views
73

是否有像Exit For这样的说法,除了不是退出循环而是移动到下一个项目。VB.NET - 如何移动到下一个项目a For Each Loop?

例如:

For Each I As Item In Items 

    If I = x Then 
     ' Move to next item 
    End If 

    ' Do something 

Next 

我知道可能只是一个Else添加if语句,因此内容如下:

For Each I As Item In Items 

    If I = x Then 
     ' Move to next item 
    Else 
     ' Do something 
    End If 

Next 

只是不知道是否有跳的方式到Items列表中的下一个项目。我相信大多数人会正确地问为什么不使用Else声明,但对我来说,包装“做某事”代码似乎不太可读。特别是当有更多的代码时。

回答

141
For Each I As Item In Items 
    If I = x Then Continue For 

    ' Do something 
Next 
+0

感谢这正是我正在寻找,有趣的如何它不在MSDN文档? (http://msdn.microsoft.com/en-us/library/5ebk1751.aspx)还祝贺打了Jon整个帖子,整整20秒! :) – 2009-05-06 14:01:48

+5

我几乎得到了Skeeted一次! ;) – 2009-05-06 14:04:44

41

我会用Continue语句来代替:

For Each I As Item In Items 

    If I = x Then 
     Continue For 
    End If 

    ' Do something 

Next 

请注意,这是在移动迭代器本身略有不同 - 任何前If将再次执行。通常这是你想要的,但如果没有,你必须明确地使用GetEnumerator(),然后使用MoveNext()/Current,而不是使用For Each循环。

3

关于什么:

If Not I = x Then 

    ' Do something ' 

End If 

' Move to next item ' 
2

我要明确的是,下面的代码是不是好的做法。您可以使用GOTO标签:

For Each I As Item In Items 

    If I = x Then 
     'Move to next item 
     GOTO Label1 
    End If 

    ' Do something 
    Label1: 
Next 
+15

你可以,但请不要。 – MiseryIndex 2009-05-06 14:10:04

1

当我试图Continue For它失败了,我得到了一个编译器错误。在做这件事时,我发现了'恢复':

For Each I As Item In Items 

    If I = x Then 
     'Move to next item 
     Resume Next 
    End If 

    'Do something 

Next 

注意:我在这里使用VBA。