Thursday, April 28, 2011

How do I access Collection keys during For Each in VB.net ?

I have some code like this:

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

How can I get both the value and key within the loop? Maybe there is another class that makes this easier?

From stackoverflow
  • I'd use a generic dictionary...

     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
    
    DisgruntledGoat : I'm getting the error, "KeyValuePair is not defined". Any ideas?
    Pavel Minaev : `Imports System.Collections.Generic`
    Tim Hoolihan : good catch, I updated the answer

0 comments:

Post a Comment