c# Dictionary、ConcurrentDictionary的使用

编程入门 行业动态 更新时间:2024-10-24 05:21:44

c# <a href=https://www.elefans.com/category/jswz/34/1769667.html style=Dictionary、ConcurrentDictionary的使用"/>

c# Dictionary、ConcurrentDictionary的使用

Dictionary

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

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

using System;
using System.Collections.Generic;
using System.Linq;class Program
{static void Main(){// 创建一个DictionaryDictionary<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"]}");// 遍历Dictionaryforeach (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}");}}
}

更多推荐

c# Dictionary、ConcurrentDictionary的使用

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

发布评论

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

>www.elefans.com

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