C# 基础 Dictionary(字典)和ConcurrentDictionary(线程安全的字典)

编程入门 行业动态 更新时间:2024-10-25 16:28:38

一、Dictionary
Dictionary<TKey, TValue> 泛型类提供了键值对的映射。通过键来检索值的速度是非常快的,接近于 O(1),这是因为 Dictionary<TKey, TValue> 类是作为一个哈希表来实现的。检索速度取决于为 TKey 指定的类型的哈希算法的质量。TValue可以是值类型,数组,类或其他。

Dictionary是一种变种的HashTable,它采用一种分离链接散列表的数据结构来解决哈希冲突的问题。命名空间System.Collection.Generic

Dictionary属性和方法
1、Dictionary一些常用的属性

属性描述
Comparer获取用于确定字典中的键是否相等的 IEqualityComparer
Count获取包含在 Dictionary<TKey, TValue> 中的键/值对的数目
Item获取或设置与指定的键相关联的值
Keys获取包含 Dictionary<TKey, TValue> 中的键的集合
Values获取包含 Dictionary<TKey, TValue> 中的值的集合

2、Dictionary一些常用的方法

方法描述
Add将指定的键和值添加到字典中
Clear从 Dictionary<TKey, TValue> 中移除所有的键和值
ContainsKey确定 Dictionary<TKey, TValue> 是否包含指定的键
ContainsValue确定 Dictionary<TKey, TValue> 是否包含特定值
Equals(Object)确定指定的 Object 是否等于当前的 Object
Finalize允许对象在“垃圾回收”回收之前尝试释放资源并执行其他清理操作
GetEnumerator返回循环访问 Dictionary<TKey, TValue> 的枚举器
GetHashCode用作特定类型的哈希函数
GetObjectData实现 System.Runtime.Serialization.ISerializable 接口,并返回序列化 Dictionary<TKey, TValue> 实例所需的数据
GetType获取当前实例的 Type
MemberwiseClone创建当前 Object 的浅表副本
OnDeserialization实现 System.Runtime.Serialization.ISerializable 接口,并在完成反序列化之后引发反序列化事件
Remove从 Dictionary<TKey, TValue> 中移除所指定的键的值
ToString返回表示当前对象的字符串
TryGetValue获取与指定的键相关联的值

实例

using System;
using System.Collections;
using System.Collections.Generic;

namespace WebApp
{
    class Program
    {
        static void Main(string[] args)
        {
            Dictionary<string, string> myDic = new Dictionary<string, string>();
            
            //插入
            myDic.Add("1", "Dictionary");
            myDic.Add("2", "Dictionary2");
            myDic.Add("3", "Dictionary3");

            //key 存在
            try
            {
                myDic.Add("1", "DictionaryNew");
            }
            catch
            {
                Console.WriteLine("Key = \"1\" already exists.");
            }
            //取值
            Console.WriteLine("key = \"2\", value = {0}.", myDic["2"]);

            //修改
            myDic["2"] = "DictionaryNew2";
            myDic["4"] = "Dictionary4";   //修改的key不存在则新增
            Console.WriteLine("key = \"2\", value = {0}.", myDic["2"]);
            Console.WriteLine("key = \"4\", value = {0}.", myDic["4"]);

            //判断key是否存在
            if (!myDic.ContainsKey("5"))
            {
                myDic.Add("5", "Dictionary5");
                Console.WriteLine("key = \"5\": {0}", myDic["5"]);
            }
             //移除
            myDic.Remove("1");

            if (!myDic.ContainsKey("1"))
            {
                Console.WriteLine("Key \"1\" is not found.");
            }
            //foreach 取值
            foreach (var item in myDic)
            {
                Console.WriteLine("Key = {0}, Value = {1}", item.Key, item.Value);
            }
            //遍历字典
		    //foreach (KeyValuePair<string, string> kvp in myDic)
		    //{
		        //Console.WriteLine("Key = {0}, Value = {1}", kvp.Key, kvp.Value);
		    //}

            //所有的值
            foreach (var item in myDic.Values)
            {
                Console.WriteLine("Value = {0}",item);
            }

            //所有的key
            foreach (var item in myDic.Keys)
            {
                Console.WriteLine("Key = {0}", item);
            }
            Console.ReadKey();
        }
    }
}

结果

Key = "1" already exists. 
key = "2", value = Dictionary2. 
key = "2". value = DictionaryNew2. 
key = "4". value = Dictionary4. 
key = "5": Dictionary5 
Key "1" is not found.
Key = 2. Value = DictionaryNew2 
Key = 3. Value = Dictionary3 
Key = 4. Value = Dictionary4 
Key = 5. Value — Dictionary5 
Value = DictionaryNew2 
Value = Dictionary3 
Value = Dictionary4 
Value = DictionaryS
Key = 2 
Key = 3 
Key = 4 
Key = 5

二、ConcurrentDictionary
ConcurrentDictionary<TKey,TValue> 类表示可由多个线程同时访问的键/值对的线程安全集合。命名空间:System.Collections.Concurrent

ConcurrentDictionary属性和方法
1、ConcurrentDictionary的常用属性

属性描述
Count获取包含在 ConcurrentDictionary<TKey,TValue> 中的键/值对的数目。
IsEmpty获取一个值,该值指示 ConcurrentDictionary<TKey,TValue> 是否为空。
Item[TKey]获取或设置与指定的键关联的值。
Keys获得一个包含 Dictionary<TKey,TValue> 中的键的集合。
Values获取包含 Dictionary<TKey,TValue> 中的值的集合。

2、ConcurrentDictionary的常用方法

方法描述
AddOrUpdate(TKey, Func<TKey,TValue>, Func<TKey,TValue,TValue>)如果该键不存在,则使用第一个函数将键/值对添加到 ConcurrentDictionary<TKey,TValue>;如果该键已存在,则使用第二个函数更新 ConcurrentDictionary<TKey,TValue> 中的键/值对。
AddOrUpdate(TKey, TValue, Func<TKey,TValue,TValue>)如果该键不存在,则将键/值对添加到 ConcurrentDictionary<TKey,TValue> 中;如果该键已经存在,则通过使用指定函数更新 ConcurrentDictionary<TKey,TValue> 中的键/值对。
Clear()将所有键和值从 ConcurrentDictionary<TKey,TValue> 中移除。
ContainsKey(TKey)确定是否 ConcurrentDictionary<TKey,TValue> 包含指定键。
Equals(Object)确定指定的对象是否等于当前对象。
GetEnumerator()返回遍历 ConcurrentDictionary<TKey,TValue> 的枚举器
GetHashCode()作为默认哈希函数。
GetOrAdd(TKey, Func<TKey,TValue>)如果该键不存在,则通过使用指定的函数将键/值对添加到 ConcurrentDictionary<TKey,TValue> 中。 如果该键存在,则返回新值或现有值。
GetOrAdd(TKey, TValue)如果该键不存在,则将键/值对添加到 ConcurrentDictionary<TKey,TValue> 中。 如果该键存在,则返回新值或现有值。
public KeyValuePair<TKey,TValue>[] ToArray()将 ConcurrentDictionary<TKey,TValue> 中存储的键和值对复制到新数组中。
ToString()返回表示当前对象的字符串。
TryAdd(TKey, TValue)尝试将指定的键和值添加到 ConcurrentDictionary<TKey,TValue> 中。
TryGetValue(TKey, TValue)尝试从 ConcurrentDictionary<TKey,TValue> 获取与指定的键关联的值。
TryRemove(TKey, TValue)尝试从 ConcurrentDictionary<TKey,TValue> 中移除并返回具有指定键的值。
TryUpdate(TKey, TValue, TValue)如果具有 key 的现有值等于 comparisonValue,则将与 key 关联的值更新为 newValue。

更多推荐

C# 基础 Dictionary(字典)和ConcurrentDictionary(线程安全的字典)

本文发布于:2023-06-14 09:47:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1462970.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:字典   线程   基础   Dictionary   ConcurrentDictionary

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!