2011-09-21 45 views
0

如何从迭代中获取vb.net集合中的密钥值?如何从集合中获取密钥和值V​​B.Net

Dim sta As New Collection 
    sta.Add("New York", "NY") 
    sta.Add("Michigan", "MI") 
    sta.Add("New Jersey", "NJ") 
    sta.Add("Massachusetts", "MA") 

    For i As Integer = 1 To sta.Count 
     Debug.Print(sta(i)) 'Get value 
     Debug.Print(sta(i).key) 'Get key ? 
    Next 

回答

3

很确定你不能直接从Microsoft.VisualBasic.Collection

对于上面的示例代码,请考虑使用System.Collections.Specialized.StringDictionary。如果这样做,请注意,Add方法具有从VB集合中反转的参数 - 首先键值,然后是值。

Dim sta As New System.Collections.Specialized.StringDictionary 
sta.Add("NY", "New York") 
'... 

For Each itemKey in sta.Keys 
    Debug.Print(sta.Item(itemKey)) 'value 
    Debug.Print(itemKey) 'key 
Next 
2

我不推荐使用的集合类,因为这是在VB兼容库,使迁移VB6程序更容易。将其替换为System.Collections或System.Collections.Generic命名空间中的许多类之一。

+1

我同意。我一直使用泛型但是我已经提供了一个dll,我没有控制权返回一个带有键的集合。 – TroyS

1

使用反射可以得到一个关键。

Private Function GetKey(Col As Collection, Index As Integer) 
    Dim flg As BindingFlags = BindingFlags.Instance Or BindingFlags.NonPublic 
    Dim InternalList As Object = Col.GetType.GetMethod("InternalItemsList", flg).Invoke(Col, Nothing) 
    Dim Item As Object = InternalList.GetType.GetProperty("Item", flg).GetValue(InternalList, {Index - 1}) 
    Dim Key As String = Item.GetType.GetField("m_Key", flg).GetValue(Item) 
    Return Key 
End Function 

不使用VB.Collection建议,但有时我们正在处理的代码,当它在过去使用。请注意,使用无证私人方法并不安全,但没有其他解决方案的地方是合理的。

更多deailed信息可以在SO发现:How to use reflection to get keys from Microsoft.VisualBasic.Collection

0

是的,它可能很好,但我想建议更换您使用其他收藏。

如何处理Reflection,类型Microsoft.VisualBasic.Collection包含一些专用字段,在这种情况下应该使用的字段是“m_KeyedNodesHash”字段,字段类型是System.Collections.Generic。 Dictionary(Of String,Microsoft.VisualBasic.Collection.Node),它包含一个名为“Keys”的属性,返回类型为System.Collections.Generic.Dictionary(Of String,Microsoft.VisualBasic.Collection.Node).KeyCollection ,获得某个关键字的唯一方法是将其转换为IEnumerable(Of String)类型,并调用ElementAt函数。

Private Function GetKey(ByVal col As Collection, ByVal index As Integer) 
    Dim listfield As FieldInfo = GetType(Collection).GetField("m_KeyedNodesHash", BindingFlags.NonPublic Or BindingFlags.Instance) 
    Dim list As Object = listfield.GetValue(col) 
    Dim keylist As IEnumerable(Of String) = list.Keys 
    Dim key As String = keylist.ElementAt(index) 
    Return key 
End Function