C#中字典的常用操作有哪些

c#
647
2024/9/11 12:31:41
栏目: 编程语言
开发者测试专用服务器限时活动,0元免费领,库存有限,领完即止! 点击查看>>

在C#中,Dictionary<TKey, TValue>是一种非常常用的数据结构,用于存储键值对。以下是一些常用的字典操作:

  1. 创建字典

使用new关键字创建一个空字典,或者使用集合初始化器添加初始元素。

var dictionary = new Dictionary<string, int>();

// 或者使用集合初始化器
var dictionary2 = new Dictionary<string, int>
{
    {"one", 1},
    {"two", 2},
    {"three", 3}
};
  1. 添加元素

使用Add方法将键值对添加到字典中。

dictionary.Add("four", 4);
  1. 访问元素

通过键访问字典中的值。

int value = dictionary["two"]; // value = 2
  1. 修改元素

通过键修改字典中的值。

dictionary["two"] = 20; // 将键 "two" 的值修改为 20
  1. 删除元素

使用Remove方法删除指定键的元素。

dictionary.Remove("two"); // 删除键 "two" 及其对应的值
  1. 检查键是否存在

使用ContainsKey方法检查字典中是否存在指定的键。

bool exists = dictionary.ContainsKey("one"); // exists = true
  1. 获取字典中的所有键和值

使用KeysValues属性分别获取字典中的所有键和值。

foreach (string key in dictionary.Keys)
{
    Console.WriteLine(key);
}

foreach (int value in dictionary.Values)
{
    Console.WriteLine(value);
}
  1. 遍历字典

使用foreach循环遍历字典中的键值对。

foreach (KeyValuePair<string, int> kvp in dictionary)
{
    Console.WriteLine($"Key: {kvp.Key}, Value: {kvp.Value}");
}
  1. 清空字典

使用Clear方法清空字典中的所有元素。

dictionary.Clear();
  1. 获取字典的大小

使用Count属性获取字典中的元素数量。

int count = dictionary.Count;

这些是C#字典的一些常用操作。请注意,字典的键必须是唯一的,但值可以重复。如果尝试添加一个已经存在的键,将会抛出一个ArgumentException异常。

辰迅云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>

推荐阅读: c#中dispose的用法是什么