【问题标题】:How to access value with known key from a nested dictionary如何使用嵌套字典中的已知键访问值
【发布时间】:2016-07-26 15:39:18
【问题描述】:

我创建了一个字典

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 的值

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

【问题讨论】:

  • 类似sbuild.AppendLine(item.Key & ") " & item.Value("y7x1"))?
  • 谢谢你,马克我刚刚学习。
  • 这表明我的字典正在工作。现在我必须弄清楚如何在循环之外单独访问它们。

标签: .net vb.net dictionary


【解决方案1】:

我有工作

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

【讨论】:

    【解决方案2】:

    考虑过使用 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 的值 2...

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-08-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-02-16
      • 2021-11-10
      • 2021-03-04
      相关资源
      最近更新 更多