1.初始化一个键值对
1 //初始化定义一个键值对,注意最后的括号
2 Dictionary dic = new Dictionary();
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 kv in dic)
3 {
4 Console.WriteLine("键为:{0},值为:{1}", kv.Key, kv.Value);
5 }
using System;
using System.Collections.Generic;
namespace _09键值对
{
class Program
{
static void Main(string[] args)
{
//Dictionary
//定义一个键值对集合
Dictionary dictionary = new Dictionary();
//添加键值对数据,键必须唯一,值可重复
dictionary.Add("1", "张珊");
dictionary.Add("2", "李四");
dictionary.Add("3", "王五");
dictionary.Add("4", "王八");
//重赋值
dictionary["3"] = "沈继涵";
//判断集合中是否含有某一个键ContainsKey()
if (!dictionary.ContainsKey("5"))
{
dictionary.Add("5", "杨过");//不含则加
}
else
{
dictionary["5"] = "杨过";//含则改
}
Console.WriteLine(dictionary["5"]);
//用foreach
//通过键遍历集合
foreach (string item in dictionary.Keys)
{
Console.WriteLine("键--{0} 值--{1}", item, dictionary[item]);
}
//通过键值对遍历集合
foreach (KeyValuePair kv in dictionary)
{
Console.WriteLine("键--{0} 值--{1}", kv.Key, kv.Value);
}
Console.ReadKey();
}
}
}