Dictionary基礎定義:
spa
Demo:key爲int類型,值爲string類型繼承
初始化string
Dictionary<int,string> dic=new Dictionary<int,string>();it
添加元素 io
dic.Add(1,"C#");基礎
dic.Add(2,"Java");object
經過key查找元素foreach
if(dic.ContainsKey(1))循環
{遍歷
key(主鍵)=1;
value(數據列)=dic[1];
}
經過keyValuePair遍歷元素
foreach(keyValuePair<int,string>kvp in dic)
{
Console.WriteLine("key={0},value{1}",kvp.key,key.value);
key(主鍵)=kvp.key;
key(數據列)=kvp.value;
}
近遍歷鍵keys屬性
Dictionary<int,string>.keyConllection keycol=dic.keys;
foreach(int key in keycol)
{
key(主鍵)=key;
}
僅遍歷values屬性
Dictionary<int,string>.ValueConllection valcol=dic.values;
foreach(string value in valcol)
{
value(數據列值)=value;
}
經過Remove方法移除指定的鍵值
dic.Remove(1);
if(dic.ContainsKey(1))
{
key=1;
value=key[1]
}
else {
Console.WriteLine("不存在key:1");
}
Dictionary經常使用屬性和方法: