tags:

views:

5039

answers:

4

Hi,

Is there a statment like Exit For, except instead of exiting the loop it just moves to the next item.

For example:

For Each I As Item In Items

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

' Do something

Next

I know could simply add an Else to the If statment so it would read as follows:

For Each I As Item In Items

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

Next

Just wondering if there is a way to jump to the next item in the Items List. Im sure most will proberly be asking why not ust use the else statment, but to me wrapping the "Do Something" code seems to be less readable especcially, when there is a lot more code.

+17  A: 
For Each I As Item In Items
    If I = x Then Continue For

    ' Do something
Next
Adam Robinson
Thanks this is exactly what i was looking for, funny how its not in the MSDN documentation?? (http://msdn.microsoft.com/en-us/library/5ebk1751.aspx) Also congrats on beating Jon to the post, by a whole 20 seconds! :)
Sean Taylor
I nearly got Skeeted once again! ;)
Adam Robinson
+4  A: 

I'd use the Continue statement instead:

For Each I As Item In Items

If I = x Then
    Continue For
End If

' Do something

Next

Note that this is slightly different to moving the iterator itself on - anything before the If will be executed again. Usually this is what you want, but if not you'll have to use GetEnumerator() and then MoveNext()/Current explicitly rather than using a For Each loop.

Jon Skeet
+1  A: 

What about:

If Not I = x Then

  ' Do something '

End If

' Move to next item '
timo2oo8
A: 

I want to clear this thing that following code is not good practice. you can use GOTO Label

For Each I As Item In Items

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

' Do something
Label1:
Next
Syed Tayyab Ali
You could, but please don't.
MiseryIndex
Due to jump, therefore it is bad.
Syed Tayyab Ali