10

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?

Mark Biek
  • 146,731
  • 54
  • 156
  • 201
David Basarab
  • 72,212
  • 42
  • 129
  • 156

5 Answers5

22
foreach(string key in hashTable.Keys)
{
   Console.WriteLine(String.Format("{0}: {1}", key, hashTable[key]));
}
Ben Scheirman
  • 40,531
  • 21
  • 102
  • 137
10

I like:

foreach(DictionaryEntry entry in hashtable)
{
    Console.WriteLine(entry.Key + ":" + entry.Value);
}
gkrogers
  • 8,126
  • 3
  • 29
  • 36
Jake Pearson
  • 27,069
  • 12
  • 75
  • 95
3

   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
  • 52,922
  • 30
  • 133
  • 149
1

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
  • 29,277
  • 14
  • 101
  • 140
1

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
  • 72,212
  • 42
  • 129
  • 156