using System;
using System.Collections.Generic;
namespace _09键值对
{
class Program
{
static void Main(string[] args)
{
//Dictionary
//定义一个键值对集合
Dictionary<string, string> dictionary = new Dictionary<string, string>();
//添加键值对数据,键必须唯一,值可重复
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<string, string> kv in dictionary)
{
Console.WriteLine("键--{0} 值--{1}", kv.Key, kv.Value);
}
Console.ReadKey();
}
}
}