C#中的Dictionary的使用
在工作中有时候会用到Dictionary,由于自己之前没用过,参考了一下前人和先辈的实践,仿照着写了一个Test,第一次用还不是很熟练,要多实践练习才能用的得心应手,写代码重在敲键盘,以此为诫。(主要注意下这个Dictionary的key和value以及添加数据方式)
写了三个方法和一个Student类。
1 namespace DictionaryTest 2 { 3 class Program 4 { 5 static void Main(string[] args) 6 { 7 DicSample1(); 8 DicSample2(); 9 DicSample3(); 10 Console.ReadLine(); 11 } 12 13 public static void DicSample1() 14 { 15 Dictionary<string, string> dic = new Dictionary<string, string>(); 16 if (dic.ContainsKey("Item1") == false) 17 { 18 dic.Add("Item1", "ZheJiang"); 19 } 20 if (dic.ContainsKey("Item2") == false) 21 { 22 dic.Add("Item2", "ShangHai"); 23 } 24 else 25 { 26 dic["Item2"] = "ShangHai"; 27 } 28 if (dic.ContainsKey("Item3") == false) 29 { 30 dic.Add("Item3", "BeiJing"); 31 } 32 if (dic.ContainsKey("Item1")) 33 { 34 Console.WriteLine("Output:" + dic["Item1"]); 35 } 36 //遍历key 37 foreach (var key in dic.Keys) 38 { 39 Console.WriteLine("Output key :{0}" , dic.Keys); 40 } 41 //遍历value 42 foreach (var value in dic.Values) 43 { 44 Console.WriteLine("Output value :{0}", dic.Values); 45 } 46 47 foreach (var d in dic) 48 { 49 Console.WriteLine("Output key:{0}, value:{1}", d.Key, d.Value); 50 } 51 } 52 53 public static void DicSample2() 54 { 55 Dictionary<string, string[]> dics = new Dictionary<string, string[]>(); 56 string[] ZheJiang = { "Hangzhou", "Huzhou", "Taizhou", "Wenzhou", "Quzhou" }; 57 string[] AnHui = { "Hefei", "Wuhu", "Huainan", "Fuyang", "Huangshan" }; 58 dics.Add("ZJ", ZheJiang); 59 dics.Add("AH", AnHui); 60 for (int i = 0; i <= ZheJiang.Count() - 1; i++) 61 { Console.WriteLine("Output:" + dics["ZJ"][i]); } 62 for (int j = 0; j < AnHui.Count() - 1; j++) 63 { Console.WriteLine("Output:" + dics["AH"][j]); } 64 } 65 66 public static void DicSample3() 67 { 68 Dictionary<string, Student> dics = new Dictionary<string, Student>(); 69 Student student = null; 70 for (int i = 0; i < 3; i++) 71 { 72 student = new Student(); 73 student.Num = i.ToString(); 74 student.Name = "Student Name" + i.ToString(); 75 dics.Add(i.ToString(), student); 76 } 77 foreach (var stuItem in dics) 78 { 79 Console.WriteLine("Output: key{0},Num{1},Name{2}", stuItem.Key, stuItem.Value.Num, stuItem.Value.Name); 80 } 81 } 82 } 83 public class Student 84 { 85 public string Name { get; set; } 86 public string Num { get; set; } 87 } 88 }
以下是运行结果: