What is a Hashtable?
A Hashtable is a collection type object that is used to store key-value combinations. In a way, it's very similar to a good old Dictionary object. You can retrieve stored value/object by either keys or by associated value. However, the performance is at its best when you search with keys.
Let's see how we can create and use a hashtable:
Dim htCars As New Hashtable
Dim myCar As String
myCar = htCars.Item(2)
This code fragment creates a hashtable object and adds three items to it. Then it calls the Item property to get the value for item with key 2. Item is the default value for the hashtable so myCar = htCars(2) would have produce the same result.
OK, so you've got a hashtable built and can get a single value out of it. But how do you iterate through all the items that were stored in it?
One way to do this is to use the Keys collection to pull out the values:
Dim carID As Integer
For Each carID In htCars.Keys
Console.Writeline(carID & " - " & htCars(carID))
Another way is to use the DictionaryEntry object as in:
Dim dictEntry As DictionaryEntry
For Each dictEntry In htCars
Console.Writeline(dictEntry.Key & " - " & dictEntry .Value)
And last but not least, you can run through all the items stored in the hashtable by obtaining the enumerator object through the IDictionaryEnumerator which is returned by the GetEnumerator function:
Dim myEnumerator As IDictionaryEnumerator = htCars.GetEnumerator()
Console.Writeline(myEnumerator.Key & " - " & myEnumerator.Value)
Hashtable are easy to use, efficient & fast. I often use it to preload frequently use data like reference tables and it really improves the application performance nicely.