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

c# 遍历dictionary

作者:资本principal   发布日期:2026-02-24   浏览:81

using System;
using System.Collections.Generic;

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

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

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

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

        // 方法三:使用 for 循环和索引器(不推荐,因为 Dictionary 不支持直接索引访问)
        Console.WriteLine("\n方法三:使用 for 循环(不推荐)");
        int index = 0;
        var keys = new List<string>(dictionary.Keys);
        for (index = 0; index < dictionary.Count; index++)
        {
            string key = keys[index];
            Console.WriteLine($"Key = {key}, Value = {dictionary[key]}");
        }
    }
}

解释说明:

  1. 创建 Dictionary

    • 使用 Dictionary<string, int> 创建一个字典对象,并初始化一些键值对。
  2. 方法一:使用 foreach 遍历键值对

    • foreach 遍历 KeyValuePair<string, int> 类型的元素,可以直接获取每个键值对的键和值。
  3. 方法二:使用 foreach 分别遍历键和值

    • 分别遍历字典的键和值。通过 dictionary.Keys 获取所有键,通过 dictionary.Values 获取所有值。
    • 注意,通过键访问值时会有一些性能开销,因此如果只需要键或值,可以分开遍历。
  4. 方法三:使用 for 循环和索引器(不推荐)

    • 字典不支持直接通过索引访问元素,因此需要将键转换为列表再进行索引访问。这种方法效率较低,一般不推荐使用。

希望这些代码和解释能帮助你理解如何遍历 C# 中的 Dictionary。

上一篇:c#枚举类型enum用法

下一篇:c# restsharp

大家都在看

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