Yato
Yato

Reputation: 3

VB.Net List inside a list within a loop

I'm doing something for a colleague and I can't seem to store a list within a list, the first element in the List Of(List Of()) object seems to be overwritten by the previously specified list instead of adding another list inside the list, contrary as what I would want to do like: {{a, b, c}, {d, e, f}, {g, h, i}, {and, so, forth}} where I would like to access it like so: listDim(0)(0):

Dim questionCont As New List(Of List(Of String))
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
    For i As Integer = 1 To numItems
        Dim questionData As New List(Of String)

        Dim getQuestionCMD As New OleDbCommand("SELECT * FROM tbl_questionnaire WHERE ID=" + i.ToString, connection)
        Dim questionItems As OleDbDataReader = getQuestionCMD.ExecuteReader()

        While (questionItems.Read)
            questionData.Add(questionItems("question"))
            questionData.Add(questionItems("item1"))
            questionData.Add(questionItems("item2"))
            questionData.Add(questionItems("item3"))
            questionData.Add(questionItems("item4"))
            questionData.Add(questionItems("answer"))
        End While

        questionCont.Add(questionData)
        questionData.Clear()
    Next
End Sub

Upvotes: 0

Views: 370

Answers (2)

Yato
Yato

Reputation: 3

Fixed! It seems that the error was on my part since introducing a .Clear() when a New List(Of String) had already been declared inside the loop will clear the contents of the List(Of String) instance. So, removing the .Clear() fixed it. An oversight.

Upvotes: 0

trucker_jim
trucker_jim

Reputation: 572

Not strictly an answer but I think the problem is elsewhere in your code. I tested this snippet in debug mode to prove that lists within lists work:

Dim lst1 As New List(Of List(Of String))
For i = 0 To 3
    Dim lst2 As New List(Of String)
    lst2.Add(i.ToString & " item 1")
    lst2.Add(i.ToString & " item 2")
    lst2.Add(i.ToString & " item 3")
    lst1.Add(lst2)
Next
Dim str = lst1(2)(2)

Upvotes: 1

Related Questions