C# - 字典Dictionary<TKey, TValue>

本文关键字:TKey TValue gt lt 字典 Dictionary | 更新日期: 2023-09-12 17:39:29

Dictionary<TKey, TValue>是一个泛型集合,不按特定顺序存储键值对。

字典特征

  • Dictionary<TKey, TValue>存储键值对。
  • 属于System.Collections.Generic命名空间。
  • Implements IDictionary interface.
  • 键必须是唯一的,不能为空。
  • 值可以为 null 或重复。
  • 可以通过在索引器中传递关联的键来访问值,例如 myDictionary[key]
  • 元素存储为 KeyValuePair 对象。

创建字典

可以通过传递 Dictionary<TKey, TValue> 对象可以存储的键和值的类型来创建该对象。 以下示例演示如何创建字典并添加键值对。

Example: Create Dictionary and Add Elements

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 键和字符串值。 同样,cities是一个Dictionary<string, string>类型的字典,因此它可以存储字符串键和字符串值。 字典不能包含重复键或空键,而值可以是重复键或空键。 键必须是唯一的,否则将引发运行时异常。

访问字典元素

可以使用索引器访问字典。指定键以获取关联的值。 还可以使用 ElementAt() 方法从指定的索引获取KeyValuePair

Example: Access Dictionary Elements

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() 方法。

Example: Update Dictionary Elements

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() 方法删除字典的所有元素。

Example: Remove Dictionary Elements

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

字典类层次结构

下图说明了泛型字典类层次结构。