Dictionary提供快速的基於鍵值的元素查找。
結構是:Dictionary <[key] , [value] >,當你有很多元素的時候可以用它。
它包含在System.Collections.Generic名控件中。在使用前,你必須聲明它的鍵類型和值類型。
1 using System; 2 using System.Collections.Generic; 3 using System.Linq; 4 using System.Text; 5 using System.Threading.Tasks; 6 7 namespace Demo1 8 { 9 class Program 10 { 11 static void Main(string[] args) 12 { 13 //創建泛型哈希表,Key類型為int,Value類型為string 14 Dictionary<int, string> myDictionary = new Dictionary<int, string>(); 15 //1.添加元素 16 myDictionary.Add(1, "a"); 17 myDictionary.Add(2, "b"); 18 myDictionary.Add(3, "c"); 19 //2.刪除元素 20 myDictionary.Remove(3); 21 //3.假如不存在元素則添加元素 22 if (!myDictionary.ContainsKey(4)) 23 { 24 myDictionary.Add(4, "d"); 25 } 26 //4.顯示容量和元素個數 27 Console.WriteLine("元素個數:{0}",myDictionary.Count); 28 //5.通過key查找元素 29 if (myDictionary.ContainsKey(1)) 30 { 31 Console.WriteLine("key:{0},value:{1}","1", myDictionary[1]); 32 Console.WriteLine(myDictionary[1]); 33 } 34 //6.通過KeyValuePair遍歷元素 35 foreach (KeyValuePair<int,string>kvp in myDictionary) 36 { 37 Console.WriteLine("key={0},value={1}", kvp.Key, kvp.Value); 38 39 } 40 //7.得到哈希表鍵的集合 41 Dictionary<int, string>.KeyCollection keyCol = myDictionary.Keys; 42 //遍歷鍵的集合 43 foreach (int n in keyCol) 44 { 45 Console.WriteLine("key={0}", n); 46 } 47 //8.得到哈希表值的集合 48 Dictionary<int, string>.ValueCollection valCol = myDictionary.Values; 49 //遍歷值的集合 50 foreach( string s in valCol) 51 { 52 Console.WriteLine("value:{0}",s); 53 } 54 //9.使用TryGetValue方法獲取指定鍵對應的值 55 string slove = string.Empty; 56 if (myDictionary.TryGetValue(5, out slove)) 57 { 58 Console.WriteLine("查找結果:{0}", slove); 59 } 60 else 61 { 62 Console.WriteLine("查找失敗"); 63 } 64 //10.清空哈希表 65 //myDictionary.Clear(); 66 Console.ReadKey(); 67 } 68 } 69 }
運行結果: