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

c# dictionary 遍历

作者:金钱打造势力狗。   发布日期:2025-03-12   浏览:245

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 遍历键值对");
        foreach (KeyValuePair<string, int> kvp in dictionary)
        {
            Console.WriteLine($"Key = {kvp.Key}, Value = {kvp.Value}");
        }

        // 方法二:使用 foreach 分别遍历键和值
        Console.WriteLine("\n方法二:使用 foreach 分别遍历键和值");
        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 循环和索引器(不推荐)");
        var keys = new List<string>(dictionary.Keys);
        for (int i = 0; i < keys.Count; i++)
        {
            Console.WriteLine($"Key = {keys[i]}, Value = {dictionary[keys[i]]}");
        }
    }
}

解释说明:

  1. 创建 Dictionary:首先创建一个 Dictionary<string, int> 类型的字典对象,并初始化一些键值对。
  2. 方法一:使用 foreach 遍历键值对:通过 foreach 遍历 KeyValuePair<string, int>,可以直接访问每个键值对的键和值。
  3. 方法二:使用 foreach 分别遍历键和值:分别遍历字典的键和值。可以通过 dictionary.Keys 获取所有键,通过 dictionary.Values 获取所有值。
  4. 方法三:使用 for 循环和索引器(不推荐):虽然可以将键存储在一个列表中并通过索引访问,但这种方法效率较低且不推荐。

以上代码展示了三种不同的遍历 Dictionary 的方法,其中前两种是最常用和推荐的方式。

上一篇:c# post请求

下一篇:c# out ref

大家都在看

c# 二进制

c# tcp client

c# type.gettype

c# sqlconnection

.net和c#

c#游戏开发

c#网络编程

c# rectangle

c# if else

c# rtsp

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

Laravel 中文站