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

c#键值对

作者:狂刀血斧   发布日期:2026-02-23   浏览:30

using System;
using System.Collections.Generic;

class Program
{
    static void Main()
    {
        // 创建一个字典来存储键值对
        Dictionary<string, string> dictionary = new Dictionary<string, string>();

        // 添加键值对
        dictionary.Add("key1", "value1");
        dictionary.Add("key2", "value2");
        dictionary.Add("key3", "value3");

        // 通过键访问值
        Console.WriteLine("Key1 的值是: " + dictionary["key1"]);

        // 检查键是否存在
        if (dictionary.ContainsKey("key2"))
        {
            Console.WriteLine("Key2 存在,其值是: " + dictionary["key2"]);
        }

        // 遍历字典中的所有键值对
        foreach (var item in dictionary)
        {
            Console.WriteLine($"键: {item.Key}, 值: {item.Value}");
        }

        // 删除一个键值对
        dictionary.Remove("key3");

        // 输出删除后的字典内容
        Console.WriteLine("删除 key3 后的字典内容:");
        foreach (var item in dictionary)
        {
            Console.WriteLine($"键: {item.Key}, 值: {item.Value}");
        }
    }
}

解释说明:

  1. 创建字典:使用 Dictionary<string, string> 创建一个键和值都是字符串类型的字典。
  2. 添加键值对:使用 Add 方法向字典中添加键值对。
  3. 访问值:通过键直接访问对应的值。
  4. 检查键是否存在:使用 ContainsKey 方法检查某个键是否存在于字典中。
  5. 遍历字典:使用 foreach 循环遍历字典中的所有键值对。
  6. 删除键值对:使用 Remove 方法删除指定键的键值对。

上一篇:c# button

下一篇:c# byte[] 转string

大家都在看

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 中文站