了解 C# 词典
字典是 C# 中一种功能强大的数据结构,但经常被低估和未充分利用。 Dictionary 类是 System.Collections.Generic 命名空间中的一个通用集合。 在视频" 10 分钟或更短时间内掌握 C# 中的字典数据结构"中, Tim Corey提供了一个简洁实用的指南,介绍如何在 C# 应用程序中有效地使用字典。 本文将详细解读 Tim 的解释和示例,旨在帮助您轻松掌握 C# 字典的基本知识。
词典入门
Tim 首先介绍了 C# 中的字典概念。 他将其比作一本现实生活中的字典,你在其中查找一个单词(键)来找到它的定义(值)。 在 C# 中,字典是键值对的集合,其中每个键都是唯一的且不能为空。
创建字典
在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 exceptionrookieOfTheYear.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")。
如果键不存在,字典将不返回任何输出,从而防止因访问不存在的键而导致的错误。
扩展词典功能
Tim 在 (5:33) 处进一步阐述了字典的功能,创建了一个更复杂的示例,其中字典可以将字符串映射到字符串列表:
// 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]检索该列表中的第一个项目。
结论
蒂姆在(9:00)总结发言中强调了理解字典的重要性。 他指出,虽然字典可能不经常使用,但对于需要唯一键和高效查找的场景来说,字典非常有用。
要点总结
*创建字典:了解如何使用各种数据类型初始化字典。
*添加元素:了解唯一键的重要性以及如何处理重复键异常。
*访问值:使用键高效地检索值。
*检查键是否存在:在访问值之前检查键是否存在,以防止错误。
*高级用法:实现更复杂的字典,例如以列表为值的字典。
*迭代:使用循环访问和显示字典中的所有元素。
通过观看 Tim Corey 的视频,您可以掌握 C# 中字典的使用方法,增强您的编程工具包,以应对需要高效数据检索和存储的场景。 请访问Tim 的频道,观看更多关于 C# 的实用视频。


