using System;
using System.Collections.Generic;
class Program
{
static void Main()
{
// 创建一个哈希映射(Hash Map),在C#中通常使用Dictionary类来实现。
Dictionary<string, int> hashMap = new Dictionary<string, int>();
// 添加键值对到哈希映射中
hashMap.Add("Alice", 23);
hashMap.Add("Bob", 30);
hashMap.Add("Charlie", 28);
// 访问哈希映射中的值
Console.WriteLine("Alice's age: " + hashMap["Alice"]);
// 检查键是否存在
if (hashMap.ContainsKey("Bob"))
{
Console.WriteLine("Bob's age: " + hashMap["Bob"]);
}
// 遍历哈希映射
foreach (var item in hashMap)
{
Console.WriteLine(item.Key + ": " + item.Value);
}
// 删除键值对
hashMap.Remove("Charlie");
// 输出删除后的哈希映射
Console.WriteLine("After removing Charlie:");
foreach (var item in hashMap)
{
Console.WriteLine(item.Key + ": " + item.Value);
}
}
}
创建哈希映射:在C#中,Dictionary<TKey, TValue> 类用于实现哈希映射。这里我们创建了一个 Dictionary<string, int> 类型的变量 hashMap,表示键为字符串类型、值为整数类型的哈希映射。
添加键值对:使用 Add 方法可以向哈希映射中添加键值对。例如,hashMap.Add("Alice", 23) 将键 "Alice" 和值 23 添加到哈希映射中。
访问值:通过键可以直接访问对应的值,例如 hashMap["Alice"] 返回 Alice 对应的年龄。
检查键是否存在:使用 ContainsKey 方法可以检查某个键是否存在于哈希映射中。
遍历哈希映射:使用 foreach 循环可以遍历哈希映射中的所有键值对。
删除键值对:使用 Remove 方法可以从哈希映射中删除指定的键值对。
输出结果:最后,程序会输出删除某个键值对后的哈希映射内容。
上一篇:c# @
下一篇:c#创建数组
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站