Sunday, July 24, 2005

Traversing Hash Tables

I was talking to an engineer the other day who was just starting out with C# and he had a program that maintained a hash table. But for one part of his program he wanted to iterate through all the elements of the table.

Now for a non keyed collection such as an ArrayList you can use a simple foreach statement for the base type of the collection. So for example if you had an ArrayList of Int32's you would write the following:

foreach (Int32 myint in MyArrayListCollection)
{
// myint contains an element from the collection
}

Now to iterate through a hash table you need to iterate using a DictionaryEntry. So again for example, if you had a hash table containing a load of Int32 objects you would need to write:

foreach (DictionaryEntry dict in m_MyHashTable)
{
// myint contains an element from the collection
Int32 myint = dict.Value as Int32;
}

Or you could use an Enumerator:

public static void PrintKeysAndValues( Hashtable myList )
{
IDictionaryEnumerator myEnumerator = myList.GetEnumerator();
Console.WriteLine( "\t-KEY-\t-VALUE-" );

while ( myEnumerator.MoveNext() )
Console.WriteLine("\t{0}:\t{1}", myEnumerator.Key, myEnumerator.Value);
Console.WriteLine();
}

Nothing to complex, but if this new C# coder needed to know this, then I'm sure it would be usefull for someone else too.

0 Comments:

Post a Comment

<< Home