Stampa le chiavi e i dati di una tabella hash in C# .NET 1.1
Domanda
Ho bisogno di eseguire il debug di un vecchio codice che utilizza una Hashtable per memorizzare la risposta da vari thread.
Ho bisogno di un modo per esaminare l'intero Hashtable e stampare sia le chiavi che i dati in Hastable.
Come si può fare?
Soluzione
foreach(string key in hashTable.Keys)
{
Console.WriteLine(String.Format("{0}: {1}", key, hashTable[key]));
}
Altri suggerimenti
Mi piace:
foreach(DictionaryEntry entry in hashtable)
{
Console.WriteLine(entry.Key + ":" + entry.Value);
}
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();
}
da: http://msdn.microsoft.com/en-us/library/system.collections.hashtable(VS.71).aspx
Questo dovrebbe funzionare praticamente per ogni versione del framework...
foreach (string HashKey in TargetHash.Keys)
{
Console.WriteLine("Key: " + HashKey + " Value: " + TargetHash[HashKey]);
}
Il trucco è che puoi ottenere un elenco/raccolta di chiavi (o valori) di un determinato hash su cui scorrere.
MODIFICARE:Wow, provi a abbellire un po' il tuo codice e poi sai che ci sono 5 risposte...8^D
Ho anche scoperto che funzionerà anche questo.
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);
}
Grazie per l'aiuto.
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow