c# 键值对基本用法
电脑版发表于:2017/10/11 17:21
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");myDictionary.Add(5,"Core");
3、通过Key查找元素
if(myDictionary.ContainsKey(1)) { Console.WriteLine("Key:{0},Value:{1}","1", myDictionary[1]); }
4、遍历元素
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"); }