Search code examples
vb.netfor-loopvariablesdeclaration

Variable declaration syntax error in the for next loop


Following code is working properly.

Private Sub Button1_Click(sender As Object, e As RoutedEventArgs) Handles Button1.Click
    Dim Dictionary1 As New Dictionary(Of String, Integer)
    Dim Dictionary2 As New Dictionary(Of String, Integer)
    Dim Dictionary3 As New Dictionary(Of String, Integer)
    Dim Dictionary4 As New Dictionary(Of String, Integer)
    Dim Dictionary5 As New Dictionary(Of String, Integer)

    Dictionary1.Add("George", "36")
    Dictionary2.Add("George", "36")
    Dictionary3.Add("George", "36")
    Dictionary4.Add("George", "36")
    Dictionary5.Add("George", "36")
End Sub

I have tried to shorten the above code like the below code via for next loop.

But the below code gives me an error.

Private Sub Button2_Click(sender As Object, e As RoutedEventArgs) Handles Button2.Click
    Dim Dictionary1 As New Dictionary(Of String, Integer)
    Dim Dictionary2 As New Dictionary(Of String, Integer)
    Dim Dictionary3 As New Dictionary(Of String, Integer)
    Dim Dictionary4 As New Dictionary(Of String, Integer)
    Dim Dictionary5 As New Dictionary(Of String, Integer)

    For i As Integer = 1 To 5
        ("Dictionary" & i).Add("George", "36")
    Next
End Sub

So, how can I solve the following error?

Error in the picture


Solution

  • List of Dictionary

        Dim Dictionary1 As New Dictionary(Of String, Integer)
        Dim Dictionary2 As New Dictionary(Of String, Integer)
        Dim Dictionary3 As New Dictionary(Of String, Integer)
        Dim Dictionary4 As New Dictionary(Of String, Integer)
        Dim Dictionary5 As New Dictionary(Of String, Integer)
    
        Dim ds As New List(Of Dictionary(Of String, Integer))
        ds.Add(Dictionary1)
        ds.Add(Dictionary2)
        ds.Add(Dictionary3)
        ds.Add(Dictionary4)
        ds.Add(Dictionary5)
    
        For Each d As Dictionary(Of String, Integer) In ds
            d.Add("George", 37)
        Next