c# 中Dictionary 的使用

在 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# 中的基本使用方法,通过这些操作可以方便地管理键值对集合。

<think>我们正在回答用户关于C#Dictionary使用方法的请求。用户要求提供示例。根据引用内容,我们可以总结出以下关键点:1. Dictionary是泛型类,用于存储键值对,键必须唯一。2.创建Dictionary使用`Dictionary<TKey, TValue>`并初始化。3.添加元素:使用Add方法,注意键不能重复,否则会抛出异常。4.访问元素:通过键来访问值,如`dict[key]`,如果键不存在会抛出异常。5.检查键是否存在:使用ContainsKey方法。6.安全获取值:使用TryGetValue方法,避免键不存在时的异常。7.删除元素:使用Remove方法。8.遍历Dictionary:可以使用foreach循环,遍历KeyValuePair。我们将按照以下结构组织回答:1.创建Dictionary2.添加元素3.访问元素4.检查键是否存在5.安全获取值(TryGetValue)6.删除元素7.遍历Dictionary8.其他注意事项(如初始化器、容量等)同时,我们将提供示例代码,并确保代码格式正确(使用代码块)。最后,生成相关问题。注意:引用内容中提供了一些示例,我们可以参考并整合。</think>### C# Dictionary 使用方法详解 `Dictionary<TKey, TValue>` 是 C# 中高效的键值对集合,适用于快速查找场景。以下是核心用法和示例: #### 1. **创建与初始化** ```csharp // 创建空字典 Dictionary<string, int> scores = new Dictionary<string, int>(); // 使用集合初始化器 Dictionary<string, string> countries = new Dictionary<string, string>() { {"CN", "中国"}, {"US", "美国"}, {"JP", "日本"} }; ``` #### 2. **添加元素** ```csharp scores.Add("Alice", 90); // 标准添加 scores["Bob"] = 85; // 索引器添加(若键存在则更新值) // 安全添加(避免重复键异常) if (!scores.ContainsKey("Charlie")) { scores.Add("Charlie", 75); } ``` #### 3. **访问元素** ```csharp // 直接访问(键不存在会抛异常) int aliceScore = scores["Alice"]; // 安全访问(推荐) if (scores.TryGetValue("Bob", out int bobScore)) { Console.WriteLine($"Bob's score: {bobScore}"); } else { Console.WriteLine("Key not found"); } ``` #### 4. **删除元素** ```csharp scores.Remove("Alice"); // 删除指定键 scores.Clear(); // 清空字典 ``` #### 5. **遍历字典** ```csharp foreach (KeyValuePair<string, int> kvp in scores) { Console.WriteLine($"{kvp.Key}: {kvp.Value}"); } // 单独遍历键或值 foreach (string name in scores.Keys) { ... } foreach (int score in scores.Values) { ... } ``` #### 6. **常用方法** ```csharp bool hasAlice = scores.ContainsKey("Alice"); // 检查键 bool hasScore90 = scores.ContainsValue(90); // 检查值 int count = scores.Count; // 获取元素数量 ``` #### 7. **注意事项** - **键唯一性**:重复添加相同键会触发 `ArgumentException`[^5] - **空键禁止**:键不能为 `null`(值可为 `null`) - **性能优化**:预估容量时建议初始化指定大小,减少扩容开销 ```csharp var largeDict = new Dictionary<int, string>(capacity: 1000); ``` > 示例:检测键是否存在(引用自示例[^4]) > ```csharp > if (!countries.ContainsKey("USA")) > { > Console.WriteLine("Key USA is absent"); > } > ``` --- ### 相关问题 1. `Dictionary` 与 `Hashtable` 在 C# 中的主要区别是什么? 2. 如何实现线程安全的 `Dictionary` 操作? 3. `TryGetValue` 相比直接访问 `dict[key]` 有哪些性能优势? 4. 当字典的键是自定义类型时需要如何重写方法? 5. `ConcurrentDictionary` 在并发场景下提供了哪些特殊功能? [^1]: Dictionary 实现了 `IDictionary<TKey, TValue>` 接口,支持键值对存储 [^2]: 声明语法为 `Dictionary<TKey, TValue> dict = new Dictionary<TKey, TValue>()` [^3]: Dictionary 是无序集合,键必须唯一 [^4]: 使用 `ContainsKey` 方法检测键是否存在 [^5]: 添加重复键会抛出 `ArgumentException`,操作前需检查键是否存在
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值