C#中遍歷Hashtable的4種辦法。本站提示廣大學習愛好者:(C#中遍歷Hashtable的4種辦法)文章只能為提供參考,不一定能成為您想要的結果。以下是C#中遍歷Hashtable的4種辦法正文
直接上代碼,代碼中應用四種辦法遍歷Hashtable。
using System;
using System.Collections;
namespace HashtableExample
{
class Program
{
static Hashtable hashtable = new Hashtable();
static void Main(string[] args)
{
hashtable.Add("first", "Beijing");
hashtable.Add("second", "Shanghai");
hashtable.Add("third", "Hangzhou");
hashtable.Add("forth", "Nanjing");
//遍歷辦法一:遍歷哈希表中的鍵
foreach (string key in hashtable.Keys)
{
Console.WriteLine(hashtable[key]);
}
Console.WriteLine("--------------------");
//遍歷辦法二:遍歷哈希表中的值
foreach(string value in hashtable.Values)
{
Console.WriteLine(value);
}
Console.WriteLine("--------------------");
//遍歷辦法三:遍歷哈希表中的鍵值
foreach (DictionaryEntry de in hashtable)
{
Console.WriteLine(de.Value);
}
Console.WriteLine("--------------------");
//遍歷辦法四:遍歷哈希表中的鍵值
IDictionaryEnumerator myEnumerator = hashtable.GetEnumerator();
while (myEnumerator.MoveNext())
{
Console.WriteLine(hashtable[myEnumerator.Key]);
}
}
}
}
上面是代碼的運轉成果。
