Print out the keys and Data of a Hashtable in C# .NET 1.1
Asked Answered
P

5

11

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?

Propertius answered 29/8, 2008 at 18:1 Comment(0)
L
23
foreach(string key in hashTable.Keys)
{
   Console.WriteLine(String.Format("{0}: {1}", key, hashTable[key]));
}
Lantana answered 29/8, 2008 at 18:3 Comment(1)
@Pellet you should be able to... (from string key in hashTable.Keys select new { key, hashTable[key] })Anatropous
P
11

I like:

foreach(DictionaryEntry entry in hashtable)
{
    Console.WriteLine(entry.Key + ":" + entry.Value);
}
Ppi answered 29/8, 2008 at 18:55 Comment(1)
Console.WriteLine(entry.Key + ":" + entry.Value); // missing closing braceArevalo
S
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

Subterranean answered 29/8, 2008 at 18:4 Comment(0)
H
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

Horten answered 29/8, 2008 at 18:6 Comment(0)
P
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.

Propertius answered 29/8, 2008 at 18:10 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.