flash网站源码下载,手机网站logo,中企动力青岛分公司,商标设计查询Dictionary
Dictionary 用于存储键-值对的集合。如果需要高效地存储键-值对并快速查找#xff0c;请使用 Dictionary。
注意#xff0c;键必须是唯一的#xff0c;值可以重复。
using System;
using System.Collections.Generic;
using System.Linq;class Program
{stati…Dictionary
Dictionary 用于存储键-值对的集合。如果需要高效地存储键-值对并快速查找请使用 Dictionary。
注意键必须是唯一的值可以重复。
using System;
using System.Collections.Generic;
using System.Linq;class Program
{static void Main(){// 创建一个DictionaryDictionarystring, int ageDictionary new Dictionarystring, 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. 初始化ConcurrentDictionarystring, int dictionary new ConcurrentDictionarystring, 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});}}
}