How do I get out of nested for or loop in vb.net?
I tried using exit for but it jumped or breaked only one for loop only.
How can I make it for the following:
for each item in itemList
for each item1 in itemList1
if item1.text = "bla bla bla" then
exit for
end if
end for
end for
Unfortunately, there's no exit two levels of for
statement, but there are a few workarounds to do what you want:
Goto. In general, using goto
is considered to be bad practice (and rightfully so), but using goto
solely for a forward jump out of structured control statements is usually considered to be OK, especially if the alternative is to have more complicated code.
For Each item In itemList
For Each item1 In itemList1
If item1.Text = "bla bla bla" Then
Goto end_of_for
End If
Next
Next
end_of_for:
Dummy outer block
Do
For Each item In itemList
For Each item1 In itemList1
If item1.Text = "bla bla bla" Then
Exit Do
End If
Next
Next
Loop While False
or
Try
For Each item In itemlist
For Each item1 In itemlist1
If item1 = "bla bla bla" Then
Exit Try
End If
Next
Next
Finally
End Try
Separate function: Put the loops inside a separate function, which can be exited with return
. This might require you to pass a lot of parameters, though, depending on how many local variables you use inside the loop. An alternative would be to put the block into a multi-line lambda, since this will create a closure over the local variables.
Boolean variable: This might make your code a bit less readable, depending on how many layers of nested loops you have:
Dim done = False
For Each item In itemList
For Each item1 In itemList1
If item1.Text = "bla bla bla" Then
done = True
Exit For
End If
Next
If done Then Exit For
Next
Put the loops in a subroutine and call return
I've experimented with typing "exit for" a few times and noticed it worked and VB didn't yell at me. It's an option I guess but it just looked bad.
I think the best option is similar to that shared by Tobias. Just put your code in a function and have it return when you want to break out of your loops. Looks cleaner too.
For Each item In itemlist
For Each item1 In itemlist1
If item1 = item Then
Return item1
End If
Next
Next
Make the outer loop a while loop, and "Exit While" in the if statement.
For i As Integer = 0 To 100
bool = False
For j As Integer = 0 To 100
If check condition Then
'if condition match
bool = True
Exit For 'Continue For
End If
Next
If bool = True Then Continue For
Next