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

佐手、 提交于 2021-02-18 10:37: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?


回答1:


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



回答2:


I like:

foreach(DictionaryEntry entry in hashtable)
{
    Console.WriteLine(entry.Key + ":" + entry.Value);
}



回答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




回答4:


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




回答5:


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.



来源:https://stackoverflow.com/questions/34879/print-out-the-keys-and-data-of-a-hashtable-in-c-sharp-net-1-1

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!