c# map
时间: 2023-06-30 18:20:09 浏览: 252
C# 中的 Map 对应的是 Dictionary 类。Dictionary 类是一个泛型集合类,用于存储键值对。下面是一个简单的例子:
```csharp
Dictionary<string, int> map = new Dictionary<string, int>();
map.Add("apple", 3);
map.Add("orange", 5);
map.Add("banana", 2);
Console.WriteLine(map["apple"]); // 输出 3
Console.WriteLine(map["orange"]); // 输出 5
Console.WriteLine(map["banana"]); // 输出 2
```
在上面的例子中,我们定义了一个 Dictionary 对象,其中键是 string 类型,值是 int 类型。然后我们使用 Add 方法添加了三个键值对。最后,我们可以通过索引访问 Dictionary 对象中的值。
相关问题
C#map获取键值对应的value
在 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("键不存在!");
}
```
c# java map
C# 和 Java 中都有 Map 类,但是它们的实现略有不同。
在 C# 中,Map 对应的是 Dictionary 类,它是一个泛型集合类,用于存储键值对。
而在 Java 中,Map 是一个接口,有多个实现类,比如 HashMap、TreeMap、LinkedHashMap 等。它们都用于存储键值对,但是实现方式和特点略有不同。
下面是一个在 C# 中使用 Dictionary 类和在 Java 中使用 HashMap 类的简单例子:
在 C# 中使用 Dictionary:
```csharp
Dictionary<string, int> map = new Dictionary<string, int>();
map.Add("apple", 3);
map.Add("orange", 5);
map.Add("banana", 2);
Console.WriteLine(map["apple"]); // 输出 3
Console.WriteLine(map["orange"]); // 输出 5
Console.WriteLine(map["banana"]); // 输出 2
```
在 Java 中使用 HashMap:
```java
HashMap<String, Integer> map = new HashMap<>();
map.put("apple", 3);
map.put("orange", 5);
map.put("banana", 2);
System.out.println(map.get("apple")); // 输出 3
System.out.println(map.get("orange")); // 输出 5
System.out.println(map.get("banana")); // 输出 2
```
在上面的例子中,我们都定义了一个 Map 对象,用于存储键值对。然后我们分别使用 Add/put 方法添加了三个键值对。最后,我们可以通过索引/方法访问 Map 对象中的值。
阅读全文
相关推荐











