如何在VB.net中的For Each中访问集合密钥?

Dis*_*oat 0 vb.net arrays associative-array

我有一些这样的代码:

Dim col As Collection = New Collection
col.Add(value1, "key1")
col.Add(value2, "key2")

' later...
For Each item As String In col
    ' want to get valueX and keyX here; currently, "item" holds the value
Next
Run Code Online (Sandbox Code Playgroud)

如何在循环中获取值和键?也许还有另外一门课可以简化这一过程?

Tim*_*han 5

我会使用通用词典...

 Imports System.Collections.Generic  'at top of file

    Dim col As New Dictionary(Of String, Of Object) 'or whatever type
    col.Add("key1", value1)
    col.Add("key2", value2)    

    For Each item as KeyValuePair(of String, Object) in col
           Console.WriteLine(item.key & ": " & item.value)
    Next
Run Code Online (Sandbox Code Playgroud)

  • 导入System.Collections.Generic (4认同)