用 For Each 循环遍历 Dictionary


在 VB.NET 中,用 For Each 循环遍历 Dictionary 是最常见的方式(不能用 For i = 0 To Count - 1,因为 Dictionary 不是按索引访问的)。
✅ 遍历所有键值对(KeyValuePair)
vb.net
复制
Dim dict As New Dictionary(Of String, Integer)()
' 假设已添加一些数据
dict.Add("apple", 3)
dict.Add("banana", 5)

For Each kvp As KeyValuePair(Of String, Integer) In dict
    Console.WriteLine($"Key: {kvp.Key}, Value: {kvp.Value}")
Next
✅ 只遍历键(Keys)
vb.net
复制
For Each key As String In dict.Keys
    Console.WriteLine($"Key: {key}")
Next
✅ 只遍历值(Values)
vb.net
复制
For Each value As Integer In dict.Values
    Console.WriteLine($"Value: {value}")
Next



人声分离



欢迎关注微信公众账号ByCAD