Dictionary<string, string> dic = new Dictionary<string, string>();
dic.Add("txt", "notepad.exe");
dic.Add("bmp", "paint.exe");
//通过键获取值,输入结果是"notepad.exe"
MessageBox.Show(dic["txt"].ToString());
//循环获取所有的值
foreach (var item in dic.Values)
{
}
//循环获取所有的键
foreach (var item in dic.Keys)
{
}
下面是参考:
Dictionary<int, string> fruit = new Dictionary<int, string>();
//加入重复键会引发异常
fruit.Add(1, "苹果");
fruit.Add(2, "桔子");
fruit.Add(3, "香蕉");
fruit.Add(4, "菠萝");
//因为引入了泛型,所以键取出后不需要进行Object到int的转换,值的集合也一样
foreach (int i in fruit.Keys)
{
Console.WriteLine("键是:{0} 值是:{1}",i,fruit);
}
//删除指定键,值
fruit.Remove(1);
//判断是否包含指定键
if (fruit.ContainsKey(1))
{
Console.WriteLine("包含此键");
}
//清除集合中所有对象
fruit.Clear();