理解 C# 字典
C#中一個強大但經常被低估的資料結構是字典。 Dictionary類別是一個在System.Collections.Generic命名空間內的泛型集合。 在他的视频,"The Dictionary Data Structure in C# in 10 Minutes or Less"中,Tim Corey 提供了一个简洁和实用的指南,教您如何在C#应用程序中有效地使用字典。 這篇文章拆解了Tim的解釋和例子,旨在幫助您輕鬆掌握C#字典的要點。
字典介紹
Tim首先介紹了C#中的字典概念。 他將其比作一本現實生活中的字典,您可以查找單詞(鍵)以找到其定義(值)。 在C#中,字典是一個鍵值對的集合,其中每個鍵都是唯一的且不能為null。
創建字典
C#中的字典是使用Dictionary<TKey, TValue>語法宣告的,可以通過鍵值對進行高效的資料儲存和檢索。 在實例化時設置默認的初始容量後,當元素增加時字典可以動態調整。
在(0:28),Tim從一個基本的控制台應用程式開始示範如何創建字典。 他使用以下程式碼初始化了一個以整數為鍵,以字串為值的字典:
// Declare a dictionary with integer keys and string values
Dictionary<int, string> rookieOfTheYear = new Dictionary<int, string>();
// Declare a dictionary with integer keys and string values
Dictionary<int, string> rookieOfTheYear = new Dictionary<int, string>();
在這裡,string)。 變數rookieOfTheYear是字典實例的名稱。 您也可以將鍵類型設定為string以使用字串鍵。
添加元素到字典
現在Tim在(2:08)中向字典中添加元素。 他展示了如何使用Add方法來添加鍵值對:
// Add entries to the dictionary
rookieOfTheYear.Add(2000, "Mike Miller");
rookieOfTheYear.Add(2001, "Jane Doe");
rookieOfTheYear.Add(2002, "Jane Doe");
rookieOfTheYear.Add(2003, "John Smith");
// Add entries to the dictionary
rookieOfTheYear.Add(2000, "Mike Miller");
rookieOfTheYear.Add(2001, "Jane Doe");
rookieOfTheYear.Add(2002, "Jane Doe");
rookieOfTheYear.Add(2003, "John Smith");
此例中:
-
"Mike Miller"添加。 - 同樣,鍵
"John Smith"相關聯。
他指出,雖然值可以重複,但鍵必須是唯一的。 嘗試添加重複的鍵會導致異常:
rookieOfTheYear.Add(2001, "Jane Doe"); // This will throw an exception
rookieOfTheYear.Add(2001, "Jane Doe"); // This will throw an exception
此異常發生是因為鍵2001已經存在於字典中。
訪問字典元素
為了示範值檢索,Tim在(3:45)使用了以下程式碼行:
// Accessing a value with a specific key
Console.WriteLine(rookieOfTheYear[2002]); // Outputs: Jane Doe
// Accessing a value with a specific key
Console.WriteLine(rookieOfTheYear[2002]); // Outputs: Jane Doe
在這裡,2002相關的值。 這是一種根據鍵查找值的非常高效的方法。

檢查鍵存在與否
在(4:29),Tim討論了如何使用ContainsKey方法檢查字典中是否存在鍵:
// Check if a key exists before accessing its value
if (rookieOfTheYear.ContainsKey(2002))
{
Console.WriteLine(rookieOfTheYear[2002]);
}
// Check if a key exists before accessing its value
if (rookieOfTheYear.ContainsKey(2002))
{
Console.WriteLine(rookieOfTheYear[2002]);
}
在上述例子中,2002是否存在於字典中。 如果存在,則打印相應的值("Jane Doe")。
如果鍵不存在,字典將不輸出,從而防止訪問不存在鍵的錯誤。
擴展字典功能
在(5:33),Tim擴充字典功能,創建了一個更複雜的例子,包含將字串映射到字串列表的字典:
// Declare a dictionary with string keys and List<string> as values
Dictionary<string, List<string>> wishList = new();
// Add entries to the dictionary with lists as values
wishList.Add("Tim Corey", new List<string> { "Xbox", "Tesla", "Pizza" });
wishList.Add("Billy Bob", new List<string> { "PS5", "Ford", "Hoagie" });
wishList.Add("Mary Jane", new List<string> { "House", "Car", "Sub" });
// Declare a dictionary with string keys and List<string> as values
Dictionary<string, List<string>> wishList = new();
// Add entries to the dictionary with lists as values
wishList.Add("Tim Corey", new List<string> { "Xbox", "Tesla", "Pizza" });
wishList.Add("Billy Bob", new List<string> { "PS5", "Ford", "Hoagie" });
wishList.Add("Mary Jane", new List<string> { "House", "Car", "Sub" });
在這裡:
-
鍵是字串(例如:"Tim Corey"、"Billy Bob"、"Mary Jane")。
- 值是字串的列表,代表每個人的願望清單。
遍歷字典
在(7:24),Tim演示了如何使用foreach循環遍歷字典:
// Iterate over each key-value pair in the dictionary
foreach (var (key, value) in wishList)
{
Console.WriteLine($"{key}'s wish list:");
// Iterate over each item in the list of values
foreach (var item in value)
{
Console.WriteLine($"\t{item}");
}
}
// Iterate over each key-value pair in the dictionary
foreach (var (key, value) in wishList)
{
Console.WriteLine($"{key}'s wish list:");
// Iterate over each item in the list of values
foreach (var item in value)
{
Console.WriteLine($"\t{item}");
}
}
此例中:
-
wishList字典中的每個鍵值對。 -
key指的是鍵(例如:"Tim Corey")。 -
value指的是與該鍵相關的值的列表。 - 內循環遍歷列表中的每個項目並打印。
這樣就可以使用循環來打印所有元素,通過特定的鍵及其相應的特定值逐一訪問字典元素。 這裡是輸出:

訪問更複雜的值
Tim也展示了如何通过在(8:26)显式使用指定索引来访问字典中更复杂的值:
// Access the first item in the list of values for the specified key
Console.WriteLine(wishList["Tim Corey"][0]); // Outputs: Xbox
// Access the first item in the list of values for the specified key
Console.WriteLine(wishList["Tim Corey"][0]); // Outputs: Xbox
在這裡,[0]檢索該列表中的第一個項目。
結論
Tim在(9:00)總結時強調了理解字典的重要性。 他指出,雖然字典可能不常使用,但它們對於需要唯一鍵和高效查找的場景非常有用。
關鍵要點
-
创建字典:了解如何用多種類型初始化字典。
-
添加元素:瞭解唯一鍵的重要性及如何處理重複鍵異常。
-
訪問值:高效利用鍵檢索值。
-
檢查鍵存在與否:在訪問值之前檢查鍵存在以防止錯誤。
-
進階用法:實施更複雜的字典,例如將列表作為值的字典。
- 迭代:利用循環訪問並顯示字典中的所有元素。
透過遵循Tim Corey的影片,您可以掌握C#中字典的使用,增強您的編程工具集以應對需要高效數據檢索和存儲的場景。 查看Tim的頻道以獲取更多關於C#的資訊影片。

