C#中遍歷Hashtable的4種方法
阿新 • • 發佈:2022-03-28
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]);
}
}
}
}
|
下面是程式碼的執行結果。
- C# ArrayList、HashSet、HashTable、List、Dictionary的區別詳解
- C#常見的幾種集合 ArrayList,Hashtable,List<T>,Dictionary<K,V> 遍歷方法對比
- C#中雜湊表(HashTable)用法例項詳解(新增/移除/判斷/遍歷/排序等)
- 詳解C#中HashTable的用法
- 聊聊C# 中HashTable與Dictionary的區別說明
</div>