2015-11-15 52 views
1

很難描述,但我試圖使用List集合作爲SortedList集合中的一個參數並檢索這些值。我相信我的設置是正確的,因爲它不返回任何錯誤,但我無法檢索值(沒有返回)。有任何想法嗎?使用列表(或作爲參數)SortList

這裏是我的代碼:

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 

回答

1

你添加到主/排序列表後清零MyInnerList

MyInnerList.Clear() 

既然是,存儲在SortedList值也被清除的對象(它們是同樣的東西):

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 

產量:

1A項
物品1b中
物品圖2a
條目2b

+0

真棒!說得通。非常感謝。 – ptownbro

+0

其實......快速提問:爲什麼「testlist」變量不需要「新建」?通常,當我使用List集合然後嘗試向它添加一個值時,我總是得到「變量在被賦值之前使用」警告/錯誤,當我DON「T使用」New「時 – ptownbro

+0

你不甚至需要var'For Each s As String In kvp.Value'將會正常工作 - 編譯器知道這個值是一個List,'New'不需要,因爲你沒有創建一個新的對象;你只需要指明它的類型。 'testlist = kvp.Value' *給它一個現有的列表 – Plutonix