1. 程式人生 > 其它 >C#中遍歷Hashtable的4種方法

C#中遍歷Hashtable的4種方法

C#中遍歷Hashtable的4種方法
https://www.jb51.net/article/67977.htm

直接上程式碼,程式碼中使用四種方法遍歷Hashtable。

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 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]);       }     }   } }


下面是程式碼的執行結果。


您可能感興趣的文章:
                    </div>