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
This question is related to
vb.net
for-loop
nested-loops
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
If I want to exit a for-to loop, I just set the index beyond the limit:
For i = 1 To max
some code
if this(i) = 25 Then i = max + 1
some more code...
Next`
Poppa.
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
Put the loops in a subroutine and call return
Make the outer loop a while loop, and "Exit While" in the if statement.
Source: Stackoverflow.com