如何在不知道密钥的情况下访问哈希表的第一个值?

How to access a hashtable's first value without knowing the key?

在安装期间读取配置文件后,我将 Web 服务 url 保存到 Hashtable 中以测试与这些服务的连接。

在查看我保存的所有值之前,我只想测试第一个值。我使用的键是包含服务 url 的整个 xml 节点,所以我不知道它。

起初我对Hashtable了解不多,所以我尝试使用索引访问它。假设 ht 是填充的 Hashtable,我试过这个:

Dim serviceUrl as String = ht(0).Value

这显然失败了,因为没有 key 等于 0,而 serviceUrl 只是一个 Nothing

然后我尝试使用以下方法访问第一个元素:

Dim firstEntry as DictionaryEntry = ht(ht.Keys(0).ToString())
' Also tried this:
' Dim firstEntry as DictionaryEntry = ht(ht.Keys(0))

在这两种情况下我都得到了一个错误:

System.InvalidCastException: Specified cast is not valid.

我最终使用 For Each 并在第一次迭代后直接退出循环。

For Each entry As DictionaryEntry In ht
    Dim serviceUrl as String = entry.Value
    'Use it and exit for.
    Exit For
Next

嗯,这看起来真的很糟糕。

经过一段时间的调试和环顾四周,我使用了一个数组来保存键值:

Dim arr as Object() = new Object(100){}
'Copy the keys to that array.
ht.Keys.CopyTo(arr,0)

'Now I can directly access first item from the Hashtable:
Dim serviceUrl as String = ht(arr(0))

我不确定这是否正确。

是否有任何 direct/clean 方法从 Hashtable 访问第一项?

Keys 属性 是一个 ICollection,不是 IList,所以它不能被索引。 ICollection 基本上就是 IEnumerableCount 属性,所以你应该像 IEnumerable 一样对待它。这意味着枚举它以获得第一项。您可以使用 LINQ:

Dim firstKey = myHashtable.Keys.Cast(Of Object)().FirstOrDefault()

或者你可以老派:

Dim firstKey As Object

For Each key In myHashtable.Keys
    firstKey = key
    Exit For
Next

如果collection可能为空,可以先用Count属性测试一下