Friday, October 19, 2007

Iterate through HashTable

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.

3 comments:

Samuel said...

I know this post is over 2 years old but I figure I may as well add some feedback since this is the number 1 result on google...

There is no way (that I know of anyways) to know what order the items in the hash table were added in. The examples in this blog are great for simply seeing what is in the hashtable, but if you need to know the order of things you would be better off using something like an ArrayList()

Either way, still a good post. :)

Cheers!

Paul Shannon said...

Seriously, this helped me out so much.

Thanks very much indeed

shola said...

Thanks alot helped out just now