C#map获取键值对应的value
时间: 2023-08-03 15:06:16 浏览: 56
在 C# 中,可以使用 Dictionary<TKey, TValue> 类来实现 Map 的功能。使用 Dictionary<TKey, TValue> 类可以方便地获取 Map 中某个键对应的值。
可以使用索引器 [] 来获取某个键对应的值。例如,以下代码获取键为 "apple" 对应的值:
```csharp
Dictionary<string, int> dict = new Dictionary<string, int>();
dict.Add("apple", 3);
int value = dict["apple"];
Console.WriteLine(value); // 输出 3
```
如果要获取某个键对应的值,可以使用 TryGetValue() 方法。该方法会尝试从字典中获取指定键对应的值,如果键不存在,则返回默认值。例如,以下代码获取键为 "banana" 对应的值:
```csharp
Dictionary<string, int> dict = new Dictionary<string, int>();
dict.Add("apple", 3);
int value;
if (dict.TryGetValue("banana", out value))
{
Console.WriteLine(value);
}
else
{
Console.WriteLine("键不存在!");
}
```
完整的代码示例:
```csharp
Dictionary<string, int> dict = new Dictionary<string, int>();
dict.Add("apple", 3);
int value1 = dict["apple"];
Console.WriteLine(value1); // 输出 3
int value2;
if (dict.TryGetValue("banana", out value2))
{
Console.WriteLine(value2);
}
else
{
Console.WriteLine("键不存在!");
}
```