Laravel  
laravel
文档
数据库
架构
入门
php技术
    
Laravelphp
laravel / php / java / vue / mysql / linux / python / javascript / html / css / c++ / c#

c# hashmap

作者:自然ㄣ之光   发布日期:2025-10-29   浏览:9

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);
        }
    }
}

解释说明:

  1. 创建哈希映射:在C#中,Dictionary<TKey, TValue> 类用于实现哈希映射。这里我们创建了一个 Dictionary<string, int> 类型的变量 hashMap,表示键为字符串类型、值为整数类型的哈希映射。

  2. 添加键值对:使用 Add 方法可以向哈希映射中添加键值对。例如,hashMap.Add("Alice", 23) 将键 "Alice" 和值 23 添加到哈希映射中。

  3. 访问值:通过键可以直接访问对应的值,例如 hashMap["Alice"] 返回 Alice 对应的年龄。

  4. 检查键是否存在:使用 ContainsKey 方法可以检查某个键是否存在于哈希映射中。

  5. 遍历哈希映射:使用 foreach 循环可以遍历哈希映射中的所有键值对。

  6. 删除键值对:使用 Remove 方法可以从哈希映射中删除指定的键值对。

  7. 输出结果:最后,程序会输出删除某个键值对后的哈希映射内容。

上一篇:c# @

下一篇:c#创建数组

大家都在看

c# 二进制

c# tcp client

c# type.gettype

c# sqlconnection

c# string.format 小数位数

.net和c#

c#获取系统时间

c#游戏开发

c#网络编程

c# rectangle

Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3

Laravel 中文站