C# 键值对的使用

在C#中,键值对(Key-Value Pair)通常在字典(Dictionary<TKey, TValue>)数据结构中使用,它允许你根据一个唯一的键(Key)来存储和检索一个值(Value)。下面是如何在C#中使用键值对的一些基本示例:

创建和初始化字典

// 创建一个字典,键是字符串类型,值是整数类型
Dictionary<string, int> dictionary = new Dictionary<string, int>();

// 添加键值对
dictionary.Add("apple", 1);
dictionary.Add("banana", 2);
dictionary.Add("cherry", 3);

或者使用集合初始化器在声明时直接初始化字典:

Dictionary<string, int> dictionary = new Dictionary<string, int>
{
    {"apple", 1},
    {"banana", 2},
    {"cherry", 3}
};

访问键值对

// 通过键来获取值
int appleCount = dictionary["apple"]; // 返回1

// 或者使用 TryGetValue 方法安全地获取值,避免键不存在的情况
int count;
if (dictionary.TryGetValue("banana", out count))
{
    Console.WriteLine($"Banana count: {count}"); // 输出 Banana count: 2
}
else
{
    Console.WriteLine("Banana not found in the dictionary.");
}

修改键值对

// 修改已存在的键值对
dictionary["apple"] = 10; // 现在 "apple" 对应的值变成了 10

遍历键值对

// 使用 foreach 循环遍历字典中的所有键值对
foreach (var pair in dictionary)
{
    Console.WriteLine($"Key: {pair.Key}, Value: {pair.Value}");
}

// 或者使用 KeyValuePair<TKey, TValue> 来遍历
foreach (KeyValuePair<string, int> kvp in dictionary)
{
    Console.WriteLine($"Key: {kvp.Key}, Value: {kvp.Value}");
}

检查键是否存在和删除键值对

// 检查键是否存在
if (dictionary.ContainsKey("cherry"))
{
    Console.WriteLine("Cherry exists in the dictionary.");
}

// 删除键值对
if (dictionary.Remove("cherry")) // 如果成功删除,Remove 方法返回 true
{
    Console.WriteLine("Cherry has been removed from the dictionary.");
}

这些是键值对在C#字典中的基本用法。字典是一个非常有用的数据结构,当你需要根据某个唯一的键快速查找、添加或删除对应的值时,它是非常合适的选择。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

我写代码菜如坤

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值