1. 程式人生 > >C#中的Dictionary字典類常用方法介紹

C#中的Dictionary字典類常用方法介紹

remove span one style pre 獲取 all str 常用方法

 1 using System.Collections.Generic;//引用命名空間//Dictionary可以理解為散列集合
 2 public class DictionaryTest
 3 {
 4          public static void Main()
 5          {
 6                //1.初始化
 7                Dictionary<string, string> dicA = new Dictionary<string, string>();
 8                //2.添加元素 key,value->學號,姓名
9 dicA.Add("A01", "張三"); 10 dicA.Add("A02", "李四"); 11 dicA.Add("B03", "王五"); 12 dicA.Add("A03", "毛毛"); 13 dicA.Add("B02", "張三"); 14 15 //3.通過key刪除元素 16 dicA.Remove("A03"); 17 //4.修改值 18 dicA("
A02")="新值"; 19 20 //5.假如不存在元素則加入元素 21 if (! dicA.ContainsKey("A08")) 22 dicA.Add("A08", "哈哈"); 23 24 //6.獲取元素個數 25 int count= dicA.Count; 26 27 //7.遍歷集合 28 foreach (KeyValuePair<string
, string> kvp in dicA) 29 { 30 Console.WriteLine("學號:{0},姓名:{1}", kvp.Key, kvp.Value); 31 } 32 33 //8.遍歷鍵或值的集合 34 Dictionary<string, string>.KeyCollection allKeys = dicA.Keys; 35 Console.WriteLine("最佳女主角:"); 36 foreach (string oneKey in allKeys) 37 { 38 Console.WriteLine(oneKey); 39 } 40 41 //Dictionary<string, string>.ValueCollection allValues = dicA.Values; 42 //foreach (string oneValue in allValues) 43 //{ 44 // Console.WriteLine(oneValue); 45 //} 46 47 //9.取值 48 string stuName=dicA("A01"); 49 50 //10.清空 51 dicA.Clear(); 52 53 }

C#中的Dictionary字典類常用方法介紹