C#中应用Dictionary集合
Dictionary:指从一组键(key)到一组值的映射,每一个添加项都由一个值及相关联的键组成
键是唯一的,不能为空引用(null),值可以是空值
key和value可以是任何类型额(string、int等)
应用:
1、创建及初始化:
IDictionary<string, string> myDictionary = new Dictionary<string, string>();
2、添加元素
myDictionary.Add("USERID", userId);
myDictionary.Add("APPLICATION", appId);
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");
}