130

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
Nishantha
  • 6,065
  • 6
  • 33
  • 51
KoolKabin
  • 17,157
  • 35
  • 107
  • 145
  • 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. – ysap Aug 07 '18 at 11:34

7 Answers7

215

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
    
Heinzi
  • 167,459
  • 57
  • 363
  • 519
  • 4
    Can't say that any of those are better than the `goto` other than the function if it actually makes sense. – Chris Marisic Aug 20 '14 at 21:15
  • 4
    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. – Sharky Mar 03 '15 at 10:26
  • 1
    I prefer the `Try` / `Exit Try` approach, but I am no fan of the `goto` option. – JohnH May 25 '16 at 13:34
  • Note that the "Boolean variable" method requires multiple variables and tests as nesting level gets deeper. This becomes fugly... – ysap Aug 07 '18 at 11:30
  • 1
    @ysap - 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. – ToolmakerSteve May 26 '19 at 20:32
17

Put the loops in a subroutine and call return

Tobias Schittkowski
  • 2,221
  • 2
  • 16
  • 25
  • 1
    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. – Dan Bechard Mar 02 '16 at 22:11
  • How can it be an overhead? @Dan – Altiano Gerung May 02 '18 at 03:02
  • @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. https://en.wikipedia.org/wiki/Function_prologue – Dan Bechard May 07 '18 at 21:23
  • @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. – Altiano Gerung May 08 '18 at 01:26
  • 2
    @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. :) – Dan Bechard May 09 '18 at 21:30
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
ysap
  • 7,723
  • 7
  • 59
  • 122
  • 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. – ToolmakerSteve May 26 '19 at 20:42
3

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

Andrew Thomas
  • 2,482
  • 3
  • 25
  • 29
  • This does the exact same thing as `goto` with more instructions, more verbosity and more indentation. What's the point? – Dan Bechard Mar 02 '16 at 22:15
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
Cesar
  • 2,229
  • 1
  • 22
  • 20
  • 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. – ToolmakerSteve May 26 '19 at 20:47
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
Rohad Bokhar
  • 104
  • 9
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.