首页主机资讯如何遍历C#中的字典

如何遍历C#中的字典

时间2024-09-11 16:42:03发布访客分类主机资讯浏览388
导读:在C#中,可以使用foreach循环来遍历字典(Dictionary) using System; using System.Collections.Generic; class Program { static void Mai...

在C#中,可以使用foreach循环来遍历字典(Dictionary)

using System;
    
using System.Collections.Generic;


class Program
{

    static void Main()
    {
    
        // 创建一个字典实例
        Dictionary<
    string, int>
     dictionary = new Dictionary<
    string, int>
    ();
    
        
        // 向字典中添加元素
        dictionary.Add("apple", 1);
    
        dictionary.Add("banana", 2);
    
        dictionary.Add("orange", 3);
    

        // 使用 foreach 循环遍历字典
        foreach (KeyValuePair<
    string, int>
 entry in dictionary)
        {

            Console.WriteLine($"Key: {
entry.Key}
, Value: {
entry.Value}
    ");

        }

    }

}
    

在这个示例中,我们首先创建了一个名为dictionary的字典实例,然后向其中添加了三个元素。接下来,我们使用foreach循环遍历字典。在循环内部,我们可以访问当前键值对的键和值。最后,我们使用Console.WriteLine()输出每个键值对的信息。

声明:本文内容由网友自发贡献,本站不承担相应法律责任。对本内容有异议或投诉,请联系2913721942#qq.com核实处理,我们将尽快回复您,谢谢合作!


若转载请注明出处: 如何遍历C#中的字典
本文地址: https://pptw.com/jishu/698568.html
C#字典的容量管理策略 C#字典的键值对如何排序

游客 回复需填写必要信息