在 C# .NET 1.1 中打印出哈希表的键和数据
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/34879/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Print out the keys and Data of a Hashtable in C# .NET 1.1
提问by David Basarab
I need debug some old code that uses a Hashtable to store response from various threads.
我需要调试一些使用 Hashtable 存储来自各个线程的响应的旧代码。
I need a way to go through the entire Hashtable and print out both keys and the data in the Hastable.
我需要一种方法来遍历整个 Hashtable 并打印出 Hastable 中的键和数据。
How can this be done?
如何才能做到这一点?
采纳答案by Ben Scheirman
foreach(string key in hashTable.Keys)
{
Console.WriteLine(String.Format("{0}: {1}", key, hashTable[key]));
}
回答by Dinah
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
来自:http: //msdn.microsoft.com/en-us/library/system.collections.hashtable(VS.71).aspx
回答by Dillie-O
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 个答案...... 8^D
回答by David Basarab
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.
谢谢您的帮助。
回答by Jake Pearson
I like:
我喜欢:
foreach(DictionaryEntry entry in hashtable)
{
Console.WriteLine(entry.Key + ":" + entry.Value);
}