user3685581
user3685581

Reputation:

VB.NET Temporarily modify loop's starting value?

Suppose I have the following code:

For intA As Integer = 1 To 5
    For intB As Integer = 1 To 50
        For intC As Integer = 1 to 100
            ...
        Next intC
    Next intB
 Next intA

I want to save progress to a db table so that I can continue later on. So, suppose intA is currently 2, intB is currently 14 and intC is currently 54.

Those get saved in a table like so:

 intA     intB     intC
========================
  2        14       54

Simple enough.

When I want to continue, how can I go about setting each loop to the current, saved value?

I can't simply set the initial loops' starts to the saved values, because that would alter the entire loops' "run".

I could probably use a flag to signal a value has been stored and do something like this:

booSavedC As Boolean = IsSavedC  'This resides outside all loops, so "single shot"

For intC As Integer = 1 to 100
    If booSavedC Then
        intC = GetSavedC   'or intC = GetSavedC + 1
        booSavedC = False
    End If

    ...
Next intC

However, this renders checking the booSavedC variable every single interation, as well as checking the outer loops' (booSavedB and booSavedA) variables too, etc.

Is there a better, less "expensive" way?

Upvotes: 0

Views: 279

Answers (1)

jmcilhinney
jmcilhinney

Reputation: 54427

Based on my comment above:

You would need to use variables for the start value of the loop counters and you can set them to the values from the database. Inside each loop, simply set the relevant variable to 1, so the loop will start at 1 again on the next iteration of the parent loop.

here is an example:

Module Module1

    Sub Main()
        Console.WriteLine("iMin=1, jMin=1, kMin=1")
        RunLoops(1, 1, 1)

        Console.WriteLine()

        Console.WriteLine("iMin=2, jMin=3, kMin=4")
        RunLoops(2, 3, 4)

        Console.ReadLine()
    End Sub

    Sub RunLoops(iMin As Integer, jMin As Integer, kMin As Integer)
        For i = iMin To 5
            iMin = 1

            For j = jMin To 5
                jMin = 1

                For k = kMin To 5
                    kMin = 1

                    Console.WriteLine($"i={i}, j={j}, k={k}")
                Next
            Next
        Next
    End Sub

End Module

You don't necessarily need to reset iMin as that loop is only run through once. It's there for completeness though.

EDIT:

Based on the comment below by @the_lotus and the fact that resetting the start value for the outermost loop is unnecessary, here's some modified code:

Sub RunLoops(iMin As Integer, jMin As Integer, kMin As Integer)
    For i = iMin To 5
        For j = jMin To 5
            For k = kMin To 5
                Console.WriteLine($"i={i}, j={j}, k={k}")
            Next

            kMin = 1
        Next

        jMin = 1
    Next
End Sub

Upvotes: 3

Related Questions