2009-08-11 40 views
0

我有一些像這樣的代碼:如何在VB.net中的For Each期間訪問收集鍵?

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 

我怎樣才能在循環中同時獲得的價值和關鍵?也許還有另一個課程讓這更容易?

回答

4

我會使用一個通用字典...

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 
+0

,我發現了錯誤,「KeyValuePair沒有定義」。有任何想法嗎? – DisgruntledGoat 2009-08-11 20:17:20

+4

'Imports System.Collections.Generic' – 2009-08-11 20:22:33

+0

好趕上,我更新了答案 – 2009-08-11 20:24:55