完全指南:從基礎(chǔ)到高級應(yīng)用)
1. 什么是 C# 字典字典Dictionary是 C# 中最常用的集合類型之一它表示鍵值對的集合其中每個(gè)鍵必須是唯一的。字典基于哈希表實(shí)現(xiàn)提供了快速的查找、插入和刪除操作。2. 字典的基本用法2.1 創(chuàng)建和初始化字典以下是創(chuàng)建字典的幾種常用方式// 方式1使用構(gòu)造函數(shù) Dictionarystring, int scores new Dictionarystring, int(); // 方式2使用集合初始化器 Dictionarystring, string capitals new Dictionarystring, string { { China, Beijing }, { USA, Washington D.C. }, { Japan, Tokyo } }; // 方式3使用索引初始化器C# 6.0 Dictionarystring, int ages new Dictionarystring, int { [Alice] 25, [Bob] 30, [Charlie] 35 };2.2 添加和訪問元素// 添加元素 Dictionarystring, int inventory new Dictionarystring, int(); inventory.Add(Apples, 50); inventory[Oranges] 30; // 使用索引器添加或修改 // 訪問元素 int appleCount inventory[Apples]; // 直接訪問 Console.WriteLine($蘋果數(shù)量{appleCount}); // 安全訪問避免 KeyNotFoundException if (inventory.TryGetValue(Bananas, out int bananaCount)) { Console.WriteLine($香蕉數(shù)量{bananaCount}); } else { Console.WriteLine(未找到香蕉); }2.3 更新和刪除元素// 更新元素 inventory[Apples] 60; // 直接賦值更新 // 刪除元素 inventory.Remove(Oranges); // 刪除指定鍵 inventory.Clear(); // 清空所有元素3. 字典的常用屬性和方法屬性/方法說明示例Count獲取字典中鍵值對的數(shù)量int count inventory.Count;Keys獲取包含所有鍵的集合foreach (string key in inventory.Keys)Values獲取包含所有值的集合foreach (int value in inventory.Values)ContainsKey檢查是否包含指定鍵bool hasKey inventory.ContainsKey(Apples);ContainsValue檢查是否包含指定值bool hasValue inventory.ContainsValue(50);TryAdd嘗試添加鍵值對.NET Core 2.0bool added inventory.TryAdd(Pears, 40);4. 遍歷字典4.1 使用 foreach 循環(huán)// 遍歷所有鍵值對 foreach (KeyValuePairstring, int item in inventory) { Console.WriteLine(${item.Key}: {item.Value}); } // 只遍歷鍵 foreach (string key in inventory.Keys) { Console.WriteLine($鍵{key}); } // 只遍歷值 foreach (int value in inventory.Values) { Console.WriteLine($值{value}); }4.2 使用 LINQ 查詢// 篩選值大于 20 的項(xiàng) var filtered inventory.Where(kvp kvp.Value 20); // 按值排序 var sorted inventory.OrderBy(kvp kvp.Value); // 轉(zhuǎn)換為其他集合 Liststring keysList inventory.Keys.ToList(); int[] valuesArray inventory.Values.ToArray();5. 字典的高級特性5.1 自定義鍵的相等比較器// 創(chuàng)建不區(qū)分大小寫的字符串鍵字典 Dictionarystring, int caseInsensitiveDict new Dictionarystring, int( StringComparer.OrdinalIgnoreCase ); caseInsensitiveDict[Apple] 10; int value caseInsensitiveDict[APPLE]; // 可以找到值為 105.2 線程安全的字典ConcurrentDictionaryusing System.Collections.Concurrent; ConcurrentDictionarystring, int concurrentDict new ConcurrentDictionarystring, int(); // 線程安全的添加和更新 concurrentDict.TryAdd(Item1, 100); concurrentDict.AddOrUpdate(Item1, 200, (key, oldValue) oldValue 50);5.3 只讀字典IReadOnlyDictionaryIReadOnlyDictionarystring, int readOnlyDict inventory; // 只能讀取不能修改 int count readOnlyDict.Count; bool exists readOnlyDict.ContainsKey(Apples);6. 性能考慮和最佳實(shí)踐選擇合適的鍵類型鍵類型應(yīng)正確實(shí)現(xiàn)GetHashCode()和Equals()方法預(yù)估容量如果知道大致元素?cái)?shù)量可以在構(gòu)造函數(shù)中指定初始容量以提高性能避免頻繁擴(kuò)容字典在元素?cái)?shù)量超過容量時(shí)會自動擴(kuò)容這是一個(gè)相對昂貴的操作使用 TryGetValue 避免異常比直接使用索引器更安全且性能更好考慮使用 ConcurrentDictionary在多線程環(huán)境下需要線程安全的字典操作時(shí)7. 常見問題解答Q1字典和哈希表有什么區(qū)別DictionaryTKey, TValue是泛型類型安全的性能更好推薦使用。Hashtable是非泛型的存儲 object 類型需要裝箱拆箱性能較差。Q2字典的鍵可以是 null 嗎取決于鍵類型的定義。對于引用類型默認(rèn)情況下鍵可以為 null但自定義比較器可能會改變這一行為。Q3如何實(shí)現(xiàn)字典的深拷貝// 淺拷貝共享值引用 Dictionarystring, Listint original new Dictionarystring, Listint(); Dictionarystring, Listint shallowCopy new Dictionarystring, Listint(original); // 深拷貝需要復(fù)制值 Dictionarystring, Listint deepCopy original.ToDictionary( kvp kvp.Key, kvp new Listint(kvp.Value) );8. 總結(jié)C# 字典是處理鍵值對數(shù)據(jù)的強(qiáng)大工具具有優(yōu)秀的查找性能和豐富的功能。掌握字典的基本操作、高級特性和最佳實(shí)踐能夠幫助你在實(shí)際開發(fā)中更高效地處理數(shù)據(jù)集合。