- 1 //键值对集合初始化,声明键和值的数据类型
- 2Dictionary<string,string> dic =newDictionary<string,string>();
- 3 //添加数据
- 4dic.Add("1","张三");
- 5dic.Add("2","李四");
- 6dic.Add("3","王五");
- 7dic.Add("4","赵六");
- 8 //键值对集合中的键必须是唯一的
- 9 //键值对集合中的值是可以重复的
- 10dic.Add("5","张三");
- 11 //判断键值对集合中键是否已经含有
- 12 boolb = dic.ContainsKey("1");
- 13 Console.WriteLine(b.ToString());
- 14
- 15
- 16 //用foreach遍历键值对集合中的键值
- 17 //第一种,遍历集合中的键
- 18 foreach(varain dic.Keys)
- 19 {
- 20Console.WriteLine("键--{0} 值--{1}",a.ToString(),dic[a]);
- 21 }
- 22
- 23 Console.WriteLine();
- 24 //第二种,遍历集合中的键值对
- 25 foreach(KeyValuePair<string,string> din dic)
- 26 {
- 27Console.WriteLine("键--{0} 值--{1}",d.Key,d.Value);
- 28 }
- 29Console.ReadKey();
来源: