Breaking/exit nested for in vb.net
Asked Answered
S

7

131

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
Segmentation answered 15/3, 2011 at 13:17 Comment(1)
What VB really needs is an Exit For item variant of the statement, similar to Next item. In the "good old days" you could explicitly Next the outer loop. Today, VB gives an error. Of course, it is more "constructive" to Exit For instead.Surmullet
R
217

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
    
Rosalindarosalinde answered 15/3, 2011 at 13:39 Comment(5)
Can't say that any of those are better than the goto other than the function if it actually makes sense.Intelligencer
I am going to use that goto in a big project just to remember my programming days in qbasic, ah such innocent times. otherwise i would go for a dummy do.Overflight
I prefer the Try / Exit Try approach, but I am no fan of the goto option.Wording
Note that the "Boolean variable" method requires multiple variables and tests as nesting level gets deeper. This becomes fugly...Surmullet
@Surmullet - In my experience, its rare to need multiple boolean variables. Typically, there is a single exit condition (e.g. "done") that once it is encountered, all loop levels should be exited. Nevertheless, I prefer making a separate method, and using "Return" - this cleanly encapsulates the nested construct.Ambush
I
17

Put the loops in a subroutine and call return

Iinden answered 15/3, 2011 at 13:22 Comment(5)
It's worth noting that there is overhead associated with such a call that is not present in the simpler goto solution. Of course, if the code is reusable it should be in a function already anyway.Nisi
How can it be an overhead? @DanGlossectomy
@AltianoGerung Well, my comment above assumes the compiler doesn't optimize and inline the function call. All function calls (assuming they're not inlined by the compiler) have the overhead of the prologue and epilogue to update the base stack pointer (as well as do other things like call destructors and do garbage collection if the language supports it). This is often minutia in the grand scheme of things, but does exist and can quickly become apparent in tight loops. en.wikipedia.org/wiki/Function_prologueNisi
@Dan Well, that's beyond me LOL. I think with my use cases and how technology improve over time, I will never need to worry about it.Glossectomy
@AltianoGerung If there's anything experience has taught me, it's that with enough scale, even the smallest of problems become big enough to matter. As always, profile before you make any assumptions. :)Nisi
J
7
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
Jabot answered 1/5, 2017 at 6:2 Comment(1)
Do not use this. Its behavior is wrong. Instead see accepted answer's "boolean variable" solution from six years earlier. If it were a new approach, I would explain what makes it behave incorrectly, but its not worth doing so, as the approach was already correctly shown in that earlier answer.Ambush
G
3

Make the outer loop a while loop, and "Exit While" in the if statement.

Glomma answered 29/5, 2012 at 14:52 Comment(1)
This does the exact same thing as goto with more instructions, more verbosity and more indentation. What's the point?Nisi
S
3

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
Salmanazar answered 6/2, 2013 at 4:4 Comment(1)
No, multiple "Exit For"s does not result in the desired behavior. The first one exits the first loop, additional ones are never reached, so have no effect. Other than that suggestion, you seem to have simply repeated earlier answers.Ambush
L
0

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
Ligate answered 10/4, 2019 at 15:30 Comment(1)
I recommend showing how this applies to this question. Take the code from the question, and edit it to use this approach.Ambush
C
0

Insert a boolean value check in your loop:

If MyBreak Then
    Exit Sub
End If

Where MyBreak is toggled by a button or label clicked.

Credence answered 10/9, 2021 at 4:40 Comment(1)
Please take a moment to read through the editing help in the help center.Propend

© 2022 - 2024 — McMap. All rights reserved.