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

dictionary c#

作者:昨夜的风   发布日期:2026-04-11   浏览:21

using System;
using System.Collections.Generic;

class Program
{
    static void Main()
    {
        // 创建一个 Dictionary,键为字符串类型,值为整数类型
        Dictionary<string, int> ages = new Dictionary<string, int>();

        // 添加键值对到 Dictionary 中
        ages.Add("Alice", 30);
        ages.Add("Bob", 25);
        ages.Add("Charlie", 35);

        // 访问 Dictionary 中的元素
        Console.WriteLine("Alice 的年龄是: " + ages["Alice"]);

        // 检查键是否存在
        if (ages.ContainsKey("Bob"))
        {
            Console.WriteLine("Bob 的年龄是: " + ages["Bob"]);
        }

        // 遍历 Dictionary
        foreach (var item in ages)
        {
            Console.WriteLine($"{item.Key} 的年龄是 {item.Value}");
        }

        // 修改 Dictionary 中的值
        ages["Alice"] = 31;

        // 删除一个键值对
        ages.Remove("Charlie");

        // 输出修改后的 Dictionary
        Console.WriteLine("修改后的 Dictionary:");
        foreach (var item in ages)
        {
            Console.WriteLine($"{item.Key} 的年龄是 {item.Value}");
        }
    }
}

解释说明:

  • Dictionary<TKey, TValue> 是 C# 中的一个泛型集合类,用于存储键值对。
  • ages 是一个 Dictionary<string, int>,表示键为字符串类型,值为整数类型的字典。
  • 使用 Add 方法可以向字典中添加键值对。
  • 使用索引器(如 ages["Alice"])可以直接访问或修改特定键对应的值。
  • ContainsKey 方法用于检查字典中是否包含指定的键。
  • foreach 循环可以遍历字典中的所有键值对。
  • Remove 方法可以从字典中删除指定键的键值对。

上一篇:c# 开发

下一篇:c# folderbrowserdialog

大家都在看

c# 二进制

c# 创建目录

c# datatable group by

c# tcp client

c# type.gettype

c# sqlconnection

c# string.format 小数位数

.net和c#

c#获取系统时间

c#游戏开发

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

Laravel 中文站