Plunging into .NET Development

Weblog Pieter Gheysens
Microsoft .NET Development - C# - Enterprise Library - Visual Studio 2005 Team System - Compuware DevPartner - ...

Thursday, August 11

Looping in a Hashtable

A hashtable is a class in the System.Collections namespace and represents a collection of key-and-value pairs that are organized based on the hash-code of the key. Hashtables are very useful when storing temporary key-value data in memory for quick access. The key of the hashtable is processed through a hashing function that is designed to generate a unique value that is then used as an index into the hashtable to the specific location containing the value. Hashtables strike a balance between resource usage and speed.

You can loop through the Hashtable in various ways (like a number of stuff in .NET). I will show two ...
  •       private void loopWithEnumerator(Hashtable hashTable)


             //Set the enumerator for the elements of the dictionary

             IDictionaryEnumerator enumerator = hashTable.GetEnumerator();

             //Loop into collection

             while (enumerator.MoveNext())


                Console.WriteLine("key : " + enumerator.Key.ToString());

                Console.WriteLine("value : " + enumerator.Value.ToString());



  •       private void loopWithDictionaryEntry(Hashtable hashTable)


             //Loop into HashTable

             foreach (DictionaryEntry dictionaryEntry in hashTable)


                Console.WriteLine("key : " + dictionaryEntry.Key.ToString());

                Console.WriteLine("value : " + dictionaryEntry.Value.ToString());



I prefer the one with the DictionaryEntry because you can immediately start looping through the hashtable without creating an enumerator (= extra line of code). The foreach statement is actually a wrapper around the enumerator but this won't make a difference in performance I guess ...


Post a Comment

Links to this post:

Create a Link

<< Home