Enumerate Items in a Hashtable

Problem

You need to enumerate over the contents of a Hashtable.

Solution

Use the DictionaryEntry type with a For/Each block.

Discussion

With a generic collection, you perform enumeration using the type in the collection (or one of its base types). The Hashtable does not support this convention. Instead, you must iterate over a collection of DictionaryEntry objects.

There is one DictionaryEntry object for each item stored in the collection. You can retrieve the key for the item from the DictionaryEntry.Key property, and you can retrieve the item in the collection from the DictionaryEntry.Value property.

The following code demonstrates this technique on a collection that contains strings:

' Create the collection and add two ...

Get Microsoft® Visual Basic® .NET Programmer's Cookbook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.