Dictionary常用用法:以 key 的类型为 int , value的类型为string 为例
1、创建及初始化
Dictionary<int,string>myDictionary=newDictionary<int,string>();
2、添加元素
myDictionary.Add(1,"C#");
myDictionary.Add(2,"C++");
myDictionary.Add(3,"ASP.NET");
myDictionary.Add(4,"MVC");
3、通过Key查找元素
if(myDictionary.ContainsKey(1))
{
Console.WriteLine("Key:{0},Value:{1}","1", myDictionary[1]);
}
4、通过KeyValuePair遍历元素
foreach(KeyValuePair<int,string>kvp in myDictionary)
...{
Console.WriteLine("Key = {0}, Value = {1}",kvp.Key, kvp.Value);
}
5、仅遍历键 Keys 属性
Dictionary<int,string>.KeyCollection keyCol=myDictionary.Keys;
foreach(intkeyinkeyCol)
...{
Console.WriteLine("Key = {0}", key);
}
6、仅遍历值 Valus属性
Dictionary<int,string>.ValueCollection valueCol=myDictionary.Values;
foreach(stringvalueinvalueCol)
...{
Console.WriteLine("Value = {0}", value);
}
7、通过Remove方法移除指定的键值
myDictionary.Remove(1);
if(myDictionary.ContainsKey(1))
...{
Console.WriteLine("Key:{0},Value:{1}","1", myDictionary[1]);
}
else
{
Console.WriteLine("不存在 Key : 1");
}
请发表评论