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

c#字典

作者:夏威夷丶霪男   发布日期:2026-06-11   浏览:137

using System;
using System.Collections.Generic;

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

        // 向字典中添加键值对
        dictionary.Add("apple", 1);
        dictionary.Add("banana", 2);
        dictionary.Add("cherry", 3);

        // 访问字典中的值
        Console.WriteLine("The value for 'apple' is: " + dictionary["apple"]);

        // 检查字典中是否包含某个键
        if (dictionary.ContainsKey("banana"))
        {
            Console.WriteLine("The value for 'banana' is: " + dictionary["banana"]);
        }

        // 遍历字典
        foreach (KeyValuePair<string, int> kvp in dictionary)
        {
            Console.WriteLine("Key = {0}, Value = {1}", kvp.Key, kvp.Value);
        }

        // 修改字典中的值
        dictionary["apple"] = 10;

        // 删除字典中的键值对
        dictionary.Remove("cherry");

        // 打印修改后的字典
        foreach (var item in dictionary)
        {
            Console.WriteLine("Key = {0}, Value = {1}", item.Key, item.Value);
        }
    }
}

解释说明:

  1. 创建字典:使用 Dictionary<TKey, TValue> 类来创建字典,其中 TKey 是键的类型,TValue 是值的类型。在示例中,我们创建了一个键为字符串、值为整数的字典。
  2. 添加键值对:使用 Add 方法向字典中添加键值对。
  3. 访问值:通过键直接访问字典中的值。
  4. 检查键是否存在:使用 ContainsKey 方法检查字典中是否包含某个键。
  5. 遍历字典:使用 foreach 循环遍历字典中的所有键值对。
  6. 修改值:通过键直接修改字典中的值。
  7. 删除键值对:使用 Remove 方法删除字典中的键值对。

上一篇:c#开发

下一篇: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 中文站