如何使用嵌套字典

时间:2016-07-26 15:39:19

标签: .net vb.net dictionary

我创建了一个字典

Dim north_dict As New Dictionary(Of String, Dictionary(Of String, String))

在For Each循环中我

Dim dict_north As New Dictionary(Of String, String)

为north_dict中的每个键创建一个嵌套字典

每个嵌套字典都有相同的35个键 示例键y7x1,y7x2 ...

如果没有循环遍历字典,如何从嵌套字典中检索已知密钥的值?

Dim north_files() As String = Directory.GetFiles(txtbx_north_location.Text)

For Each file As String In north_files

    Dim dict_north As New Dictionary(Of String, String)

    Dim reader_for_files As New StreamReader(file)
    Dim allLines As List(Of String) = New List(Of String)

    Do While Not reader_for_files.EndOfStream
        allLines.Add(reader_for_files.ReadLine())
    Loop

    reader_for_files.Close()

    y7x1 = ReadLine(2, allLines)
    dict_north.Add("y7x1", y7x1)
    y7x2 = ReadLine(4, allLines)
    dict_north.Add("y7x2", y7x2)

    Dim result As String
    result = Path.GetFileName(file)
    north_dict.Add(result, dict_north)

下一步

这样

Dim sbuild As New StringBuilder
For Each item As KeyValuePair(Of String, Dictionary(Of String, String)) In north_dict
    sbuild.AppendLine(item.Key & ") " & item.Value.ToString)
Next
MessageBox.Show(sbuild.ToString)

产生类似

的结果

NORTH_COL_10ROW_1)System.Collections.Generic.Dictionary'2 [System.String,System.String] NORTH_COL_10ROW_10)System.Collections.Generic.Dictionary'2 [System.String,System.String]

我希望能够从NORTH_COL_4ROW_2获取实例密钥y7x1的值

我还不知道嵌套字典是否成功添加。

2 个答案:

答案 0 :(得分:1)

我有工作

Dim dictvalue As String = ""
If north_dict("NORTH_COL_4ROW_2").TryGetValue("y7x1", dictvalue) Then
    MessageBox.Show(dictvalue.ToString)
End If

答案 1 :(得分:0)

考虑过使用linq吗?这将是......像这样。这是一个有效的例子,仍然不确定我是否理解你的问题。

        For n = 1 To 100

            Dim dict_north As New Dictionary(Of String, String)

            For m = 1 To 35
                dict_north.Add("y7x" & m.ToString(), "Value for y7x " & m.ToString())
            Next

            north_dict.Add(n.ToString(), dict_north)

        Next

        Dim s = (From nd In north_dict
                 From dn In nd.Value
                 Where dn.Key = "y7x2"
                 Select nd.Key & " - " & dn.Value).ToList()

        Debug.Print(String.Join(" ,", s.ToArray()))

结果是 1 - y7x的值2,2,y7x的值2,3,y7x的值......