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