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

c# dictionary遍历

作者:尒忸旳迣鎅゛沬卜鋽旳凄涼   发布日期:2026-05-11   浏览:97

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 和 Values 属性遍历值
        Console.WriteLine("\n遍历方法三:使用 foreach 和 Values 属性遍历值");
        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 遍历 KeyValuePair 对象。KeyValuePair 包含键和值的组合,可以直接访问 KeyValue 属性。
  3. 方法二:使用 foreach 分别遍历键和值。通过 Keys 属性获取所有键,然后通过键访问对应的值。
  4. 方法三:使用 Values 属性直接遍历所有的值。
  5. 方法四:使用 for 循环和索引器遍历。这种方法不推荐,因为 Dictionary 不保证键值对的顺序。

以上代码展示了多种遍历 Dictionary 的方法,可以根据实际需求选择合适的方式。

上一篇:c# list orderby

下一篇:c# byte[]转string

大家都在看

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