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

一、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.net");
            myDic.Add("2", "Dictionary.net2");
            myDic.Add("3", "Dictionary.net3");

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

            //修改
            myDic["2"] = "DictionaryNew.net2";
            myDic["4"] = "Dictionary.net4";   //修改的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", "Dictionary.net5");
                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 = Dictionary.net2. 
key = "2". value = DictionaryNew.net2. 
key = "4". value = Dictionary.net4. 
key = "5": Dictionary.net5 
Key "1" is not found.
Key = 2. Value = DictionaryNew.net2 
Key = 3. Value = Dictionary.net3 
Key = 4. Value = Dictionary.net4 
Key = 5. Value — Dictionary.net5 
Value = DictionaryNew.net2 
Value = Dictionary.net3 
Value = Dictionary.net4 
Value = Dictionary.netS
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。
  • 9
    点赞
  • 36
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
C#中的字典Dictionary)是线程不安全的,这意味着在多个线程同时访问和修改字典时可能会引发竞态条件(race condition)和其他线程安全问题。如果你需要在多个线程中使用字典,有几种方式可以确保线程安全性: 1. 使用锁(lock):在访问或修改字典时,使用锁来确保同时只有一个线程可以进行操作。这可以通过在代码块中使用 `lock` 关键字来实现。 ```csharp private Dictionary<string, object> myDictionary = new Dictionary<string, object>(); private object dictionaryLock = new object(); // 在访问或修改字典时使用锁 lock (dictionaryLock) { // 进行字典操作 myDictionary.Add("key", "value"); } ``` 2. 使用并发字典(ConcurrentDictionary):C#提供了一个线程安全字典实现,即`ConcurrentDictionary`。它是专门为多线程环境设计的,并提供了一组原子操作来确保线程安全性。 ```csharp private ConcurrentDictionary<string, object> myDictionary = new ConcurrentDictionary<string, object>(); // 在多个线程中访问和修改字典 myDictionary.TryAdd("key", "value"); ``` 3. 使用其他线程安全的集合类:除了字典C#还提供了其他线程安全的集合类,如`ConcurrentBag`、`ConcurrentQueue`和`ConcurrentStack`等。根据你的具体需求,选择适合的集合类来确保线程安全性。 请注意,虽然使用锁或`ConcurrentDictionary`等线程安全机制可以确保字典线程安全性,但在某些情况下可能会带来一定的性能开销。因此,根据你的应用场景和性能需求,选择合适的线程安全策略是很重要的。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值