在C#中 使用Dictionary类型

在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 是处理键值对数据时非常有用的工具。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值