著名的國外設(shè)計網(wǎng)站廣州優(yōu)化防控措施
Dictionary
Dictionary 用于存儲鍵-值對的集合。如果需要高效地存儲鍵-值對并快速查找,請使用 Dictionary。
注意,鍵必須是唯一的,值可以重復(fù)。
using System;
using System.Collections.Generic;
using System.Linq;class Program
{static void Main(){// 創(chuàng)建一個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 的年齡現(xiàn)在是 {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 類似,但是支持多線程并發(fā)操作,適用于并發(fā)編程場景。
它提供了線程安全的操作,允許多個線程同時讀取和修改數(shù)據(jù),而不需要額外的鎖定。
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. 獲取元素// 嘗試獲取與指定鍵關(guān)聯(lián)的值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. 其他方法// 獲取與指定鍵關(guān)聯(lián)的值;如果鍵不存在,則使用指定的函數(shù)或值添加鍵值對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}");}}
}