C# - Dictionary<TKey, TValue>
Dictionary<TKey, TValue>
是一个泛型集合,它以无序的方式存储键值对。
字典的特点
Dictionary<TKey, TValue>
存储键值对。- 属于
System.Collections.Generic
命名空间。 - 实现了 IDictionary<TKey, TValue> 接口。
- 键必须是唯一的,且不能为 null。
- 值可以为 null 或重复。
- 可以通过在索引器中传递关联的键来访问值,例如
myDictionary[key]
。 - 元素以 KeyValuePair<TKey, TValue> 对象的形式存储。
创建字典
您可以通过传递键和值的类型来创建 Dictionary<TKey, TValue>
对象。以下示例展示了如何创建字典并添加键值对。
示例:创建字典并添加元素
IDictionary<int, string> numberNames = new Dictionary<int, string>();
numberNames.Add(1,"One"); //adding a key/value using the Add() method
numberNames.Add(2,"Two");
numberNames.Add(3,"Three");
//The following throws run-time exception: key already added.
//numberNames.Add(3, "Three");
foreach(KeyValuePair<int, string> kvp in numberNames)
Console.WriteLine("Key: {0}, Value: {1}", kvp.Key, kvp.Value);
//creating a dictionary using collection-initializer syntax
var cities = new Dictionary<string, string>(){
{"UK", "London, Manchester, Birmingham"},
{"USA", "Chicago, New York, Washington"},
{"India", "Mumbai, New Delhi, Pune"}
};
foreach(var kvp in cities)
Console.WriteLine("Key: {0}, Value: {1}", kvp.Key, kvp.Value);
在上述示例中,numberNames
是 Dictionary<int, string>
类型的字典,因此它可以存储 int 类型的键和 string 类型的值。同样,cities
是 Dictionary<string, string>
类型的字典,因此它可以存储 string 类型的键和 string 类型的值。字典不能包含重复或 null 的键,而值可以重复或为 null。键必须是唯一的,否则会抛出运行时异常。
访问字典元素
可以通过索引器访问字典。指定一个键以获取关联的值。您还可以使用 ElementAt()
方法从指定的索引获取 KeyValuePair
。
示例:访问字典元素
var cities = new Dictionary<string, string>(){
{"UK", "London, Manchester, Birmingham"},
{"USA", "Chicago, New York, Washington"},
{"India", "Mumbai, New Delhi, Pune"}
};
Console.WriteLine(cities["UK"]); //prints value of UK key
Console.WriteLine(cities["USA"]);//prints value of USA key
//Console.WriteLine(cities["France"]); // run-time exception: Key does not exist
//use ContainsKey() to check for an unknown key
if(cities.ContainsKey("France")){
Console.WriteLine(cities["France"]);
}
//use TryGetValue() to get a value of unknown key
string result;
if(cities.TryGetValue("France", out result))
{
Console.WriteLine(result);
}
//use ElementAt() to retrieve key-value pair using index
for (int i = 0; i < cities.Count; i++)
{
Console.WriteLine("Key: {0}, Value: {1}",
cities.ElementAt(i).Key,
cities.ElementAt(i).Value);
}
更新字典
通过在索引器中指定键来更新键的值。如果字典中不存在该键,它将抛出 KeyNotFoundException
,因此在访问未知键之前请使用 ContainsKey()
方法。
示例:更新字典元素
var cities = new Dictionary<string, string>(){
{"UK", "London, Manchester, Birmingham"},
{"USA", "Chicago, New York, Washington"},
{"India", "Mumbai, New Delhi, Pune"}
};
cities["UK"] = "Liverpool, Bristol"; // update value of UK key
cities["USA"] = "Los Angeles, Boston"; // update value of USA key
//cities["France"] = "Paris"; //throws run-time exception: KeyNotFoundException
if(cities.ContainsKey("France")){
cities["France"] = "Paris";
}
移除字典中的元素
Remove()
方法从字典中删除一个现有的键值对。Clear()
方法删除字典中的所有元素。
示例:移除字典元素
var cities = new Dictionary<string, string>(){
{"UK", "London, Manchester, Birmingham"},
{"USA", "Chicago, New York, Washington"},
{"India", "Mumbai, New Delhi, Pune"}
};
cities.Remove("UK"); // removes UK
//cities.Remove("France"); //throws run-time exception: KeyNotFoundException
if(cities.ContainsKey("France")){ // check key before removing it
cities.Remove("France");
}
cities.Clear(); //removes all elements
字典类层次结构
下图说明了泛型字典类的层次结构。

在 docs.microsoft.com 上了解字典的方法和属性。