views:

2439

answers:

5

I need debug some old code that uses a Hashtable to store response from various threads.

I need a way to go through the entire Hashtable and print out both keys and the data in the Hastable.

How can this be done?

+5  A: 
foreach(string key in hashTable.Keys)
{
   Console.WriteLine(String.Format("{0}: {1}", key, hashTable[key]));
}
Ben Scheirman
+1  A: 

   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();
   }

from: http://msdn.microsoft.com/en-us/library/system.collections.hashtable(VS.71).aspx

Dinah
A: 

This should work for pretty much every version of the framework...

foreach (string HashKey in TargetHash.Keys)
{
   Console.WriteLine("Key: " + HashKey + " Value: " + TargetHash[HashKey]);
}

The trick is that you can get a list/collection of the keys (or the values) of a given hash to iterate through.

EDIT: Wow, you try to pretty your code a little and next thing ya know there 5 answers... 8^D

Dillie-O
A: 

I also found that this will work too.

System.Collections.IDictionaryEnumerator enumerator = hashTable.GetEnumerator();

while (enumerator.MoveNext())
{
    string key = enumerator.Key.ToString();
    string value = enumerator.Value.ToString();

    Console.WriteLine(("Key = '{0}'; Value = '{0}'", key, value);
}

Thanks for the help.

David Basarab
A: 

I like:

foreach(DictionaryEntry entry in hashtable)
{
    Console.WriteLine(entry.Key + ":" + entry.Value);
}
Jake Pearson
Console.WriteLine(entry.Key + ":" + entry.Value); // missing closing brace
Jeremy Cron