Breaking/exit nested for in vb.net
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
Solution 1:
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 usinggoto
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
Solution 2:
Put the loops in a subroutine and call return