这里有类似的问题,但没有回答:vb.net dictionary of string,dictionary...after filling readout always empty
我用文件行填充List(Of String),然后将其添加到Dictionary中。我用来填充这个字典的方法可以正常工作。我创建:
Private dictDictionary As Dictionary(Of String, List(Of String))
循环遍历文本文件并将每行添加到列表中,然后将该列表添加到字典中,文件名为key,如下所示:
dictDictionary.Add(sFileName, sFileRows)
sFileRows是一个List(Of String),包含MAX 1056个元素,我需要根据特定选项移动它们。我遇到的问题是通过密钥访问此列表(字符串)。
我试过了:
For Each kvp As KeyValuePair(Of String, List(Of String)) In dictDictionary
Dim sKey As String = kvp.Key
Dim tempRows As List(Of String) = New List(Of String)
tempRows = dictDictionary.item(sKey)
Next
无论我在将Dictionary中的List(Of String)分配给新列表时尝试的是什么,它总是为空。但原始字典中有我从文本文件中读取的List(Of String)中的行。
第一种填充字典的方法:
Private Sub GetInfo()
Try
Dim sFileName As String = String.Empty
Dim sFileRows As List(Of String) = New List(Of String)
If IO.Directory.Exists("some directory")Then
Dim Files() As String = IO.Directory.GetFiles("directory and file type")
For Each File As String In Files
sFileName = Path.GetFileName(File)
Dim rdrRows As StreamReader = New StreamReader(File)
Dim sString As String
While rdrRows.Peek() >= 0
sString = rdrRows.ReadLine()
sFileRows.Add(sString)
End While
'Actually adding the info to the dictionary
dictDictionary.Add(sFileName, sFileRows)
rdrRows.Dispose()
sFileRows.Clear()
Next
End If
Catch ex As Exception
End Try
End Sub
操纵List(Of String)中元素顺序的第二种方法
Private Sub ChangeStructure()
For Each kvp As KeyValuePair(Of String, List(Of String)) In dictDictionary
Dim rows As List(Of String) = kvp.Value
For Each item As String In rows
MessageBox.Show(item.ToString)
Next
Next
End Sub
List(Of String)中现在没有任何内容,但是它在GetInfo()中被填充时
答案 0 :(得分:2)
应该像
一样简单Dim data = New Dictionary(Of String, List(Of String)) From _
{
{"Foo", New List(Of String) From {"1", "2", "3"}},
{"Bar", New List(Of String) From {"4", "5", "6"}}
}
For Each kvp in data
Console.WriteLine(kvp.Key & " says:")
For Each str in kvp.Value
Console.WriteLine(str)
Next
Next
答案 1 :(得分:0)
For Each kvp As KeyValuePair(Of String, List(Of String)) In dictDictionary
Dim rows As List(Of String) = kvp.Value
If rows Is Nothing Then Continue
For Each item As String in rows
'...
Next item
Next kvp
答案 2 :(得分:0)
您正在使用kvp.Key
,为什么不使用kvp.Value
?
For Each kvp As KeyValuePair(Of String, List(Of String)) In dictDictionary
Dim sKey As String = kvp.Key
Debug.Print("Filename: " & sKey)
Dim tempRows As List(Of String) = kvp.Value
Debug.Print("# of Lines: " & tempRows.Count)
Debug.Print("------------------------------")
For Each line As String In tempRows
Debug.Print(line)
Next
Debug.Print("------------------------------")
Debug.Print("")
Next
答案 3 :(得分:0)
问题在于这一行:
sFileRows.Clear()
List(Of String)是一种引用类型。填写列表并将其添加到字典后,清除它,所以当您稍后尝试访问它时它是空的。
解决方案是每次在循环中创建一个新列表。换句话说,移动这一行:
Dim sFileRows As List(Of String) = New List(Of String)
在For循环内部取消对.Clear()