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>


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM