Dictionary的用法
Dictionary的作用
Dictionary的结构为:Dictionary<[key], [value]>
对于存入对象是需要与[key]值一一对应的存入该泛型,通过某一个一定的[key]去找到对应的值,
特点有:
(1)键相当于找到对应值的唯一标识,所以不能重复;
(2)值是可以重复的
基本使用
(1)初始化对象
Dictionary<int, string> dic = new Dictionary<int, string>();//实例化对象
(2)添加元素
dic.Add(1, "猫猫");//对象打点添加
string a=dic[1];//赋值
(3)通过KeyValuePair遍历元素
foreach(KeyValuePair<int,string>kvp in dic)
...{
Console.WriteLine("Key = {0}, Value = {1}",kvp.Key, kvp.Value);
}
(4)遍历key
foreach (int key in dic.Keys)
{
Console.WriteLine("Key = {0}", key);
}
(5)遍历value
foreach (string value in dic.Values)
{
Console.WriteLine("value = {0}", value);
}
(6)添加存在的元素
try
{
dic.Add(2, "猫猫");
}
catch (ArgumentException)
{
Console.WriteLine("An element with Key = \"猫猫\" already exists.");
}
(7)删除元素
dic.Remove("猫猫");
if (!dic.ContainsKey("猫猫"))
{
Console.WriteLine("值 \"猫猫\" is not found.");
}
(8)判断键key是否存在
if (dic.ContainsKey(1)) // True
{
Console.WriteLine("An element with Key =1 exists.");
}
常见方法
(1)Add 将指定的键和值添加到字典中。
(2)Clear 从 Dictionary<TKey, TValue> 中移除所有的键和值。
(3)ContainsKey 确定 Dictionary<TKey, TValue> 是否包含指定的键。
(4)ContainsValue 确定 Dictionary<TKey, TValue> 是否包含特定值。
(4)Equals(Object) 确定指定的 Object 是否等于当前的 Object。 (继承自 Object。)
(5)Finalize 允许对象在“垃圾回收”回收之前尝试释放资源并执行其他清理操作。 (继承自 Object。)
(6)GetEnumerator 返回循环访问 Dictionary<TKey, TValue> 的枚举器。
(7)GetHashCode 用作特定类型的哈希函数。 (继承自 Object。)
(8)GetObjectData 实现 System.Runtime.Serialization.ISerializable 接口,并返回序列化 Dictionary<TKey, TValue> 实例所需的数据。
(9)GetType 获取当前实例的 Type。 (继承自 Object。)
(10)MemberwiseClone 创建当前 Object 的浅表副本。 (继承自 Object。)
(11)OnDeserialization 实现 System.Runtime.Serialization.ISerializable 接口,并在完成反序列化之后引发反序列化事件。
(12)Remove 从 Dictionary<TKey, TValue> 中移除所指定的键的值。
(13)ToString 返回表示当前对象的字符串。 (继承自 Object。)
(14)TryGetValue 获取与指定的键相关联的值