在C#中,Dictionary 是一个非常强大且灵活的集合类型,它存储键值对(Key-Value Pairs)。
Dictionary 类位于 System.Collections.Generic 命名空间中,因此在使用之前需要确保已经导入了这个命名空间。
1.创建和初始化
using System;
using System.Collections.Generic;
class Program
{
static void Main()
{
// 创建一个字符串键和整数值的字典
Dictionary<string, int> myDictionary = new Dictionary<string, int>();
// 或者使用集合初始化器
Dictionary<string, int> myDictionaryWithInitializer = new Dictionary<string, int>
{
{"Apple", 1},
{"Banana", 2},
{"Orange", 3}
};
}
}
2.添加、访问和修改元素
添加新项到字典或修改现有项可以使用 Add 方法或者直接通过索引操作
// 使用 Add 方法
myDictionary.Add("Cherry", 4);
// 直接通过索引设置值
myDictionary["Apple"] = 5; // 如果键存在,则更新其值;如果不存在,则添加新的键值对
访问元素
int value = myDictionary["Apple"]; // 获取键 "Apple" 对应的值
Console.WriteLine(value); // 输出: 5
检查键是否存在
为了避免在尝试访问不存在的键时抛出异常,可以先检查该键是否存在于字典中
if (myDictionary.ContainsKey("Apple"))
{
Console.WriteLine("Apple exists in the dictionary.");
}
遍历字典
遍历字典中的所有项可以使用 foreach 循环:
foreach (KeyValuePair<string, int> kvp in myDictionary)
{
Console.WriteLine("Key = {0}, Value = {1}", kvp.Key, kvp.Value);
}
// 或者只遍历键或值
foreach (string key in myDictionary.Keys)
{
Console.WriteLine("Key = {0}", key);
}
foreach (int value in myDictionary.Values)
{
Console.WriteLine("Value = {0}", value);
}
其他
Dictionary 提供了许多其他有用的方法和属性,如:
Remove() 方法用于从字典中删除指定键的元素
Count 属性用于获取字典中包含的元素数量等。
Dictionary 是处理键值对数据时非常有用的工具。