ptownbro
ptownbro

Reputation: 1278

Using List Within (or as argument of) A SortList

Hard to describe, but I'm trying to use a List collection as an argument within a SortedList collection and retrieve those values. I believe my setup is correct since it doesn't return any errors, but I can't retrieve the values (nothing is returned). Any ideas?

Here's my code:

Dim MySortedList As New SortedList(Of Int16, List(Of String))
Dim MyInnerList As New List(Of String)

MyInnerList.Add("Item 1a")
MyInnerList.Add("Item 1b")
MySortedList.Add(1, MyInnerList)
MyInnerList.Clear()

MyInnerList.Add("Item 2a")
MyInnerList.Add("Item 2b")
MySortedList.Add(2, MyInnerList)
MyInnerList.Clear()

Dim testlist As New List(Of String) 'not sure if needed.

For Each kvp As KeyValuePair(Of Int16, List(Of String)) In MySortedList
    testlist = kvp.Value

    For Each s As String In testlist
        Response.Write(s & "<br>")
    Next
Next

Upvotes: 1

Views: 24

Answers (1)

You cleared MyInnerList after adding to the main/SortedList:

MyInnerList.Clear()

Since it is an object, the value stored in SortedList is also cleared (they are the same thing):

Dim MySortedList As New SortedList(Of Int16, List(Of String))
Dim MyInnerList As New List(Of String)

MyInnerList.Add("Item 1a")
MyInnerList.Add("Item 1b")
MySortedList.Add(1, MyInnerList)

' create a new list object for the next one
MyInnerList = New List(Of String)

MyInnerList.Add("Item 2a")
MyInnerList.Add("Item 2b")
MySortedList.Add(2, MyInnerList)

Dim testlist As List(Of String) 'New is not needed.

For Each kvp As KeyValuePair(Of Int16, List(Of String)) In MySortedList
    testlist = kvp.Value

    ' For Each s As String In kvp.Value  will work just as well
    For Each s As String In testlist
        Console.Write(s & "<br>")
    Next
Next

Output:

Item 1a
Item 1b
Item 2a
Item 2b

Upvotes: 1

Related Questions