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

c# 哈希表

作者:洃铯哖輪   发布日期:2026-07-29   浏览:57

using System;
using System.Collections.Generic;

class Program
{
    static void Main()
    {
        // 创建一个哈希表(字典)
        Dictionary<string, int> hashTable = new Dictionary<string, int>();

        // 添加键值对到哈希表
        hashTable.Add("apple", 1);
        hashTable.Add("banana", 2);
        hashTable.Add("cherry", 3);

        // 查找哈希表中的值
        if (hashTable.ContainsKey("banana"))
        {
            Console.WriteLine("Value for 'banana': " + hashTable["banana"]);
        }

        // 遍历哈希表
        foreach (var item in hashTable)
        {
            Console.WriteLine("Key: {0}, Value: {1}", item.Key, item.Value);
        }

        // 修改哈希表中的值
        hashTable["apple"] = 10;

        // 删除哈希表中的键值对
        hashTable.Remove("cherry");

        // 输出修改后的哈希表内容
        Console.WriteLine("After modifications:");
        foreach (var item in hashTable)
        {
            Console.WriteLine("Key: {0}, Value: {1}", item.Key, item.Value);
        }
    }
}

解释说明:

  • 创建哈希表:使用 Dictionary<TKey, TValue> 类来创建哈希表,其中 TKey 是键的类型,TValue 是值的类型。在示例中,我们创建了一个 Dictionary<string, int>
  • 添加键值对:使用 Add 方法向哈希表中添加键值对。
  • 查找键值对:使用 ContainsKey 方法检查哈希表中是否存在指定的键,并通过键获取对应的值。
  • 遍历哈希表:使用 foreach 循环遍历哈希表中的所有键值对。
  • 修改值:直接通过键访问并修改对应的值。
  • 删除键值对:使用 Remove 方法从哈希表中移除指定的键值对。

上一篇:c# string数组

下一篇:c# 反序列化

大家都在看

c# 二进制

c# 创建目录

c# socket服务端连接多个客户端

c# datatable group by

c# tcp client

c# type.gettype

c# sqlconnection

c# string.format 小数位数

c# invoke方法

.net和c#

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

Laravel 中文站