c# Dictionary、ConcurrentDictionary的使用

Dictionary

Dictionary 用于存储键-值对的集合。如果需要高效地存储键-值对并快速查找,请使用 Dictionary。

注意,键必须是唯一的,值可以重复。

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

class Program
{
    static void Main()
    {
        // 创建一个Dictionary
        Dictionary<string, int> ageDictionary = new Dictionary<string, int>();

        // 添加元素
        ageDictionary["Alice"] = 25;
        ageDictionary["Bob"] = 30;

        // 检查是否包含键
        if (ageDictionary.ContainsKey("Alice"))
        {
            Console.WriteLine("存在键 'Alice'");
        }

        // 获取值
        int aliceAge = ageDictionary["Alice"];
        Console.WriteLine($"Alice 的年龄是 {aliceAge}");

        // 修改值
        ageDictionary["Alice"] = 26;
        Console.WriteLine($"Alice 的年龄现在是 {ageDictionary["Alice"]}");

        // 遍历Dictionary
        foreach (var pair in ageDictionary)
        {
            Console.WriteLine($"{pair.Key}: {pair.Value}");
        }

        // 删除元素
        ageDictionary.Remove("Alice");

        // 获取所有的键或值
        var keys = ageDictionary.Keys.ToList();
        var values = ageDictionary.Values.ToList();
    }
}

ConcurrentDictionary

ConcurrentDictionary 与 Dictionary 类似,但是支持多线程并发操作,适用于并发编程场景。
它提供了线程安全的操作,允许多个线程同时读取和修改数据,而不需要额外的锁定。

using System;
using System;
using System.Collections.Concurrent;

class TestConcurrentDictionary
{
    static void Main()
    {
        // 1. 初始化
        ConcurrentDictionary<string, int> dictionary = new ConcurrentDictionary<string, int>();

        // 2. 添加或更新元素
        // 尝试添加一个新的键值对
        dictionary.TryAdd("key1", 1);

        // 如果键不存在,则添加键值对;如果键已存在,则更新其值
        dictionary.AddOrUpdate("key1", 1, (key, oldValue) => oldValue + 1);

        // 3. 获取元素
        // 尝试获取与指定键关联的值
        int value;
        if (dictionary.TryGetValue("key1", out value))
        {
            Console.WriteLine($"Value for key1: {value}");
        }

        // 4. 删除元素
        // 尝试移除指定键的键值对
        int removedValue;
        if (dictionary.TryRemove("key1", out removedValue))
        {
            Console.WriteLine($"Removed value: {removedValue}");
        }

        // 5. 其他方法
        // 获取与指定键关联的值;如果键不存在,则使用指定的函数或值添加键值对
        int newValue = dictionary.GetOrAdd("key2", k => 2);
        Console.WriteLine($"Value for key2: {newValue}");

        // 6. 遍历
        foreach (var kvp in dictionary)
        {
            Console.WriteLine($"{kvp.Key}: {kvp.Value}");
        }
    }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值