在 Visual Basic 中,遍历 Dictionary(Of TKey, TValue)
在 Visual Basic 中,遍历 Dictionary(Of TKey, TValue) 可以通过多种方式实现,具体取决于你需要访问键、值,或者同时访问键值对。以下是一些常用的遍历方法:
1. 使用 For Each 循环遍历键值对
这是最常用的方法,通过 KeyValuePair 结构体来同时访问键和值。
vb
Module Module1
Sub Main(m.xz.sizhen.info)
Dim dict As New Dictionary(Of String, String) From {
{"Fruit1", "Apple"},
{"Fruit2", "Banana"},
{"Fruit3", "Cherry"}
}
' 遍历字典中的所有键值对
For Each kvp As KeyValuePair(Of String, String) In dict
Console.WriteLine($"Key: {kvp.Key}, Value: {kvp.Value}")
Next
End Sub
End Module
2. 遍历所有键
如果你只需要访问字典中的所有键,可以使用 Keys 属性。
vb
Module Module1
Sub Main()
Dim dict As New Dictionary(Of String, String) From {
{"Fruit1", "Apple"},
{"Fruit2", "Banana"},
{"Fruit3", "Cherry"}
}
' 遍历字典中的所有键
For Each key As String In dict.Keys
Console.WriteLine($"Key: {key}")
Next
End Sub
End Module
3. 遍历所有值
如果你只需要访问字典中的所有值,可以使用 Values 属性。
vb
Module Module1
Sub Main()
Dim dict As New Dictionary(Of String, String) From {
{"Fruit1", "Apple"},
{"Fruit2", "Banana"},
{"Fruit3", "Cherry"}
}
' 遍历字典中的所有值
For Each value As String In dict.Values
Console.WriteLine($"Value: {value}")
Next
End Sub
End Module
**4. 使用