在 C# 中,Dictionary<TKey, TValue> 是一个常用的泛型集合类,它表示键值对的集合,其中每个键都是唯一的。以下是关于 Dictionary 的详细使用方法:
1. 引入命名空间
在使用 Dictionary 之前,需要引入 System.Collections.Generic 命名空间,因为 Dictionary 类定义在这个命名空间中。
using System;
using System.Collections.Generic;
class Program
{
static void Main()
{
// 在这里使用 Dictionary
}
}
2. 创建 Dictionary 对象
可以使用以下方式创建 Dictionary 对象:
// 创建一个键为 string 类型,值为 int 类型的 Dictionary
Dictionary<string, int> studentScores = new Dictionary<string, int>();
// 创建并初始化一个 Dictionary
Dictionary<string, string> countries = new Dictionary<string, string>
{
{ "China", "Beijing" },
{ "USA", "Washington D.C." },
{ "UK", "London" }
};
3. 添加元素
可以使用 Add 方法或直接通过索引器添加元素到 Dictionary 中:
// 使用 Add 方法添加元素
studentScores.Add("Alice", 85);
studentScores.Add("Bob", 90);
// 使用索引器添加元素
studentScores["Charlie"] = 78;
4. 访问元素
可以通过键来访问 Dictionary 中的元素:
// 通过键访问元素
int aliceScore = studentScores["Alice"];
Console.WriteLine($"Alice's score: {aliceScore}");
// 检查键是否存在,避免 KeyNotFoundException
if (studentScores.ContainsKey("Bob"))
{
int bobScore = studentScores["Bob"];
Console.WriteLine($"Bob's score: {bobScore}");
}
// 使用 TryGetValue 方法安全地获取值
int charlieScore;
if (studentScores.TryGetValue("Charlie", out charlieScore))
{
Console.WriteLine($"Charlie's score: {charlieScore}");
}
5. 修改元素
可以通过键来修改 Dictionary 中的元素:
// 修改元素的值
studentScores["Alice"] = 92;
Console.WriteLine($"Alice's new score: {studentScores["Alice"]}");
6. 删除元素
可以使用 Remove 方法删除 Dictionary 中的元素:
// 删除元素
studentScores.Remove("Bob");
if (!studentScores.ContainsKey("Bob"))
{
Console.WriteLine("Bob's score has been removed.");
}
7. 遍历 Dictionary
可以使用 foreach 循环遍历 Dictionary 中的键值对、键或值:
// 遍历键值对
foreach (KeyValuePair<string, int> pair in studentScores)
{
Console.WriteLine($"{pair.Key}: {pair.Value}");
}
// 遍历键
foreach (string key in studentScores.Keys)
{
Console.WriteLine($"Key: {key}");
}
// 遍历值
foreach (int value in studentScores.Values)
{
Console.WriteLine($"Value: {value}");
}
8. 获取元素数量
可以使用 Count 属性获取 Dictionary 中元素的数量:
int count = studentScores.Count;
Console.WriteLine($"Number of students: {count}");
9. 清空 Dictionary
可以使用 Clear 方法清空 Dictionary 中的所有元素:
studentScores.Clear();
Console.WriteLine($"Number of students after clearing: {studentScores.Count}");
以上就是 Dictionary 在 C# 中的基本使用方法,通过这些操作可以方便地管理键值对集合。
1092

被折叠的 条评论
为什么被折叠?



