字典常用属性、说明:
- 名称 说明
- 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 获取与指定的键相关联的值。
-
1 //创建 key类型为int,value类型为string 2 Dictionary<int, string> mydictionary = new Dictionary<int, string>(); 3 //1.添加 4 mydictionary.Add(1,"a"); 5 mydictionary.Add(2,"b"); 6 mydictionary.Add(3,"c"); 7 8 //2.删除 根据key值删除 9 mydictionary.Remove(3); 10 11 //3.判断是否存在,不存在则添加元素 12 if (!mydictionary.ContainsKey(4)) 13 { 14 mydictionary.Add(4,"d"); 15 } 16 //4.显示容量和元素个数 17 Console.WriteLine($"元素个数:{mydictionary.Count}"); 18 //显示所有数据,通过Keyvaluepair 19 foreach (KeyValuePair<int,string> item in mydictionary) 20 { 21 Console.WriteLine($"key:{item.Key},value:{item.Value}"); 22 } 23 //清空 24 //mydictionary.Clear();