A Dictionary<TKey, TValue>
是一个泛型集合,由键/值对组成,这些键/值对不按任何顺序排序。例如,
Dictionary<int, string> country = new Dictionary<int, string>();
这里,country
是一个字典,包含 int
类型键和 string
类型值。
创建字典
要在 C# 中创建字典,我们需要使用 System.Collections.Generic
命名空间。以下是在 C# 中创建字典的方法:
// create a dictionary
Dictionary<dataType1, dataType2> dictionaryName = new Dictionary<dataType1, dataType2>();
这里,
dictionaryName
- 字典的名称dataType1
- 键的数据类型dataType2
- 值的数据类型
示例:创建字典
using System;
using System.Collections;
class Program
{
public static void Main()
{
// create a dictionary
Dictionary<int, string> country = new Dictionary<int, string>();
// add items to dictionary
country.Add(5, "Brazil");
country.Add(3, "China");
country.Add(4, "Usa");
// print value having key is 3
Console.WriteLine("Value having key 3: " + country[3]);
}
}
输出
Value having key 3: China
在上面的示例中,我们创建了一个名为 country
的字典。
键是 int
类型,值是 string
类型。
字典上的基本操作
在 C# 中,我们可以对字典执行不同的操作。在本教程中,我们将介绍一些常用的 Dictionary<TKey, TValue>
操作。
- 添加元素
- 访问元素
- 更改元素
- 移除元素
让我们详细了解如何执行这些操作。
向字典添加元素
C# 提供了 Add()
方法,我们可以使用它向字典中添加元素。例如,
using System;
using System.Collections;
class Program
{
public static void Main()
{
// create a dictionary
Dictionary<string, string> mySongs = new Dictionary<string, string>();
// add items to dictionary
mySongs.Add("Queen", "Break Free");
mySongs.Add("Free", "All right now");
mySongs.Add("Pink Floyd", "The Wall");
}
}
在上面的示例中,我们创建了一个名为 mySongs
的 Dictionary<TKey, TValue>
。
这里我们使用 Add()
方法添加了键/值对,其中:
- 键 -
"Queen"
、"Free"
和"Pink Floyd"
- 值 -
"Break Free"
、"All right now"
和"The Wall"
向字典添加元素的另一种方法
Add()
方法向字典添加元素我们可以在不使用 Add()
方法的情况下向字典中添加元素。例如,
using System;
using System.Collections;
class Program
{
public static void Main()
{
// create a dictionary and add elements
Dictionary<string, string> songs = new Dictionary<string, string>() {
{ "Queen", "Break Free" },
{ "Free", "All right now" } };
}
}
这也被称为集合初始化器。
访问字典元素
我们可以通过键访问字典中的元素。例如,
using System;
using System.Collections;
class Program
{
public static void Main()
{
// create a dictionary
Dictionary<string, string> student = new Dictionary<string, string>();
// add items to dictionary
student.Add("Name", "Susan");
student.Add("Faculty", "History");
// access the value having key "Name"
Console.WriteLine(student["Name"]);
// access the value having key "Faculty"
Console.WriteLine(student["Faculty"]);
}
}
输出
Susan History
在上面的示例中,我们使用键访问了字典中的值。
student["Name"]
- 访问键为"Name"
的值student["Faculty"]
- 访问键为"Faculty"
的值
遍历字典
在 C# 中,我们也可以使用 foreach
循环遍历字典中的每个元素。例如,
using System;
using System.Collections;
class Program
{
public static void Main()
{
// create a dictionary
Dictionary<string, string> car = new Dictionary<string, string>();
// add items to dictionary
car.Add("Model", "Hyundai");
car.Add("Price", "36K");
// iterate through the car dictionary
foreach (KeyValuePair<string, string> items in car)
{
Console.WriteLine("{0} : {1}", items.Key, items.Value);
}
}
}
输出
Model : Hyundai Price : 36K
在上面的示例中,我们使用 foreach
循环遍历了 car
。
这里,Key
和 Value
属性返回一个包含字典中键和值的集合。
更改字典元素
我们可以按如下方式更改字典中元素的值:
using System;
using System.Collections;
class Program
{
public static void Main()
{
// create a dictionary
Dictionary<string, string> car = new Dictionary<string, string>();
// add items to dictionary
car.Add("Model", "Hyundai");
car.Add("Price", "36K");
// print the original value
Console.WriteLine("Value of Model before changing: " + car["Model"]);
// change the value of "Model" key to "Maruti"
car["Model"] = "Maruti";
// print new updated value of "Model"
Console.WriteLine("Value of Model after changing: " + car["Model"]);
}
}
输出
Value of Model before changing: Hyundai Value of Model after changing: Maruti
这里,我们更改了 car
字典中 "Model"
键的值。
删除字典元素
要删除字典中的元素,我们使用:
Remove()
- 从字典中删除键/值对
例如,
using System;
using System.Collections;
class Program
{
public static void Main()
{
// create a dictionary
Dictionary<string, string> employee = new Dictionary<string, string>();
// add items to dictionary
employee.Add("Name", "Marry");
employee.Add("Role", "Manager");
employee.Add("Address", "California");
Console.WriteLine("Original Dictionary :");
// iterate through the modified dictionary
foreach (KeyValuePair<string, string> items in employee)
{
Console.WriteLine("{0} : {1}", items.Key, items.Value);
}
// remove value with key "Role"
employee.Remove("Role");
Console.WriteLine("\nModified Dictionary :");
// iterate through the modified dictionary
foreach (KeyValuePair<string, string> items in employee)
{
Console.WriteLine("{0} : {1}", items.Key, items.Value);
}
}
}
输出
Original Dictionary : Name : Marry Role : Manager Address : California Modified Dictionary : Name : Marry Address : California
在上面的示例中,我们删除了键为 "Role"
的元素。
这里,employee.Remove("Role")
从 employee
字典中删除了键/值对 "Role" : "Manager"
。
因此,当我们遍历 employee
时,我们会得到一个修改后的字典。
注意:如果要删除字典中的所有元素,请使用 Clear()
方法。
常见问题
我们也可以使用 var
关键字创建字典。例如,
using System;
using System.Collections.Generic;
class Program
{
public static void Main()
{
// create a dictionary named fruits
var fruits = new Dictionary<int, string>() {
{1, "Apple"},
{2, "Orange"},
};
// print value having key 2
Console.WriteLine(fruits[2]);
}
}
输出
Orange