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