最近使用Dictionary比较多,经过一段时间的使用,发现Dictionary和List各有千秋,这里只讨论Dictionary的基本用法,Dictionary、List、ArrayList、HashTable之间的区别以后讨论。
首先是Dictionary的基本使用规则:
命名空间:
System.Collections.Generic;
组成:键key,值value,成对出现。
数据类型:可以是任何类型,如int,string,object,自定义类型等。
数据约束:键是不可以重复的,值可以重复。
数据读取:只能通过键查找值,不能通过值查找键。
字典定义:
Dictionary<int, string> dicTest = new Dictionary<int, string>();
添加元素
int [] dicKeys = new int [] {1,2,3}; //key不能重复,所有需要先判断key是否已存在
foreach (var item in dicKeys)
{
if (!dicTest.ContainsKey(item))
{
dicTest.Add(item, "张三" + item);
}
}
移除元素
if (dicTest.ContainsKey(1)) {
dicTest.Remove(1);
}
取值
if (dicTest.ContainsKey(2)) {
string strValue = dicTest[2];
}
赋值
if (dicTest.ContainsKey(2)) {
dicTest[2] = "ZhangSan";
}
遍历所有的key
string strkeys = string.Empty;
foreach (var item in dicTest.Keys)
{
strkeys += item.ToString();
}
遍历所有的alue
string strValues = string.Empty;
dicTest.Values.ToList().ForEach(
p =>
{
strValues += p.ToString();
});
常用属性
名称 说明
Comparer 获取用于确定字典中的键是否相等的 IEqualityComparer<T>。
Count 获取包含在 Dictionary<TKey,TValue>中的键/值对的数目。
Item 获取或设置与指定的键相关联的值。
Keys 获取包含Dictionary<TKey, TValue>中的键的集合。
Values 获取包含 Dictionary<TKey,TValue>中的值的集合。
常用方法
名称 说明
Add 将指定的键和值添加到字典中。
Clear 从Dictionary<TKey, TValue>中移除所有的键和值。
ContainsKey 确定Dictionary<TKey, TValue>是否包含指定的键。
ContainsValue 确定Dictionary<TKey, TValue>是否包含特定值。
Equals(Object) 确定指定的 Object是否等于当前的Object。(继承自 Object。)
Finalize 允许对象在“垃圾回收”回收之前尝试释放资源并执行其他清理操作。(继承自 Object。)
GetEnumerator 返回循环访问Dictionary<TKey, TValue>的枚举器。
GetHashCode 用作特定类型的哈希函数。(继承自 Object。)
GetObjectData 实现System.Runtime.Serialization.ISerializable接口,并返回序列化 Dictionary<TKey,TValue>实例所需的数据。
GetType 获取当前实例的 Type。(继承自 Object。)
MemberwiseClone 创建当前 Object的浅表副本。(继承自 Object。)
OnDeserialization 实现 System.Runtime.Serialization.ISerializable接口,并在完成反序列化之后引发反序列化事件。
Remove 从Dictionary<TKey, TValue>中移除所指定的键的值。
ToString 返回表示当前对象的字符串。(继承自 Object。)
TryGetValue 获取与指定的键相关联的值。