1、命名空間:
2、描述:
1)、從一組鍵(Key)到一組值(Value)的映射,每一個添加項都是由一個值及其相關連的鍵組成
2)、任何鍵都必須是唯一的
3)、鍵不能為空引用null(VB中的Nothing),若值為引用類型,則可以為空值
4)、Key和Value可以是任何類型(string,int,custom class 等)
3、創建及初始化:
4、添加元素:
myDictionary.Add("C#",0);
myDictionary.Add("C++",1);
myDictionary.Add("C",2);
myDictionary.Add("VB",2);
5、查找元素By Key:
if(myDictionary.ContainsKey("C#"))
{
Console.WriteLine("Key:{0},Value:{1}", "C#", myDictionary["C#"]);
}
6.遍歷元素 By KeyValuePair
foreach (KeyValuePair<string, int> kvp in myDictionary)
{
Console.WriteLine("Key = {0}, Value = {1}",kvp.Key, kvp.Value);
}
7、僅遍歷鍵 By Keys 屬性:
Dictionary<string, int>.KeyCollection keyCol = myDictionary.Keys;
foreach (string key in keyCol/*string key in myDictionary.Keys*/)
{
Console.WriteLine("Key = {0}", key);
}
8、僅遍歷值By Valus屬性:
Dictionary<string, int>.ValueCollection valueCol = myDictionary.Values;
foreach (int value in valueCol)
{
Console.WriteLine("Value = {0}", value);
}
9.移除指定的鍵值By Remove方法:
myDictionary.Remove("C#");
if (myDictionary.ContainsKey("C#"))
{
Console.WriteLine("Key:{0},Value:{1}", "C#", myDictionary["C#"]);
}
else
{
Console.WriteLine("不存在 Key : C#");