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

c# 遍历字典

作者:战虎天下   发布日期:2025-07-04   浏览:61

using System;
using System.Collections.Generic;

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

        // 方法1:使用 foreach 遍历字典的键值对
        Console.WriteLine("遍历方法1:使用 foreach 遍历键值对");
        foreach (KeyValuePair<string, int> kvp in dictionary)
        {
            Console.WriteLine($"Key = {kvp.Key}, Value = {kvp.Value}");
        }

        // 方法2:使用 foreach 分别遍历键和值
        Console.WriteLine("\n遍历方法2:分别遍历键和值");
        foreach (string key in dictionary.Keys)
        {
            Console.WriteLine($"Key = {key}, Value = {dictionary[key]}");
        }

        foreach (int value in dictionary.Values)
        {
            Console.WriteLine($"Value = {value}");
        }

        // 方法3:使用 for 循环和索引器(不推荐,因为 Dictionary 不支持索引访问)
        // 注意:Dictionary 不支持直接通过索引访问元素,因此这种方法不可行。
        // 仅作参考,不建议使用。
        /*
        for (int i = 0; i < dictionary.Count; i++)
        {
            Console.WriteLine($"Key = {dictionary.Keys[i]}, Value = {dictionary.Values[i]}");
        }
        */
    }
}

解释说明:

  1. 创建字典:我们首先创建了一个 Dictionary<string, int> 类型的字典,并初始化了一些键值对。
  2. 方法1:使用 foreach 遍历键值对:这是最常用的方法,通过 KeyValuePair<TKey, TValue> 来访问每个键值对。
  3. 方法2:分别遍历键和值:可以分别遍历字典的键和值,适用于只需要键或只需要值的情况。
  4. 方法3:使用 for 循环和索引器:由于 Dictionary 不支持通过索引访问元素,这种方法是不可行的,仅供了解。

如果你需要更多帮助或有其他问题,请告诉我!

上一篇:c# newtonsoft.json

下一篇:c# api

大家都在看

c# 二进制

c# tcp client

c# type.gettype

c# sqlconnection

c# string.format 小数位数

.net和c#

c#游戏开发

c#网络编程

c# rectangle

c# 取字符串最后一个字符

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

Laravel 中文站