1.初始化一个键值对
1 //初始化定义一个键值对,注意最后的括号 2 Dictionary<int, string> dic = new Dictionary<int, string>();
2.为键值对添加元素
1 //键值对的Add函数 2 dic.Add(2, "zhao"); 3 dic.Add(4, "qian"); 4 dic.Add(6, "sun"); 5 dic.Add(8, "li");
3.键值对的ContainsKey和ContainsValue函数
1 //键值对的ContainsKey和ContainsValue函数 2 Console.WriteLine(dic[4]); 3 Console.WriteLine("键值对是否包含键2:" + dic.ContainsKey(2)); 4 Console.WriteLine("键值对是否包含键5:" + dic.ContainsKey(5)); 5 Console.WriteLine("键值对是否包含值zhao:" + dic.ContainsValue("zhao")); 6 Console.WriteLine("键值对是否包含值Zhao:" + dic.ContainsValue("Zhao"));
4.键值对的数量
1 //键值对的数量 2 Console.WriteLine("键值对包含键值数量:" + dic.Count);
5.键值对的keys属性
1 //键值对的keys属性 2 foreach (int item in dic.Keys) 3 { 4 Console.WriteLine("键为:{0},值为:{1}", item, dic[item]); 5 }
6.对键值对进行遍历
1 //对键值对进行遍历 2 foreach (KeyValuePair<int,string> kv in dic) 3 { 4 Console.WriteLine("键为:{0},值为:{1}", kv.Key, kv.Value); 5 }标签:Console,dic,Add,键值,WriteLine,操作,ContainsKey,字典 From: https://www.cnblogs.com/CS-ComputerScience/p/16812817.html