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
htCars.Add(1, "Buick")
htCars.Add(2, "Chevy")
htCars.Add(3, "GM")
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))
Next
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)
Next dictEntry
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()
While myEnumerator.MoveNext()
Console.Writeline(myEnumerator.Key & " - " & myEnumerator.Value)
End While
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.
Showing posts with label Dictionary. Show all posts
Showing posts with label Dictionary. Show all posts
Friday, October 19, 2007
Subscribe to:
Posts (Atom)
