新闻资讯

质量为本、客户为根、勇于拼搏、务实创新

< 返回新闻资讯列表

C#字典遍历时如何排序,c#如何遍历字典中的key和value

发布时间:2024-07-30 14:52:10

C#字典遍用时如何排序

在C#中,字典(Dictionary)本身是无序的数据结构,但你可以对字典的键或值进行排序后再遍历。以下是一种常见的方法:

using System;
using System.Collections.Generic;
using System.Linq;

class Program
{
    static void Main()
    {
        Dictionary<string, int> dict = new Dictionary<string, int>
        {
            {"apple", 10},
            {"banana", 5},
            {"orange", 8}
        };

        // 依照键排序
        var sortedKeys = dict.Keys.OrderBy(key => key);
        foreach (var key in sortedKeys)
        {
            Console.WriteLine($"{key}: {dict[key]}");
        }

        // 依照值排序
        var sortedValues = dict.OrderBy(pair => pair.Value);
        foreach (var pair in sortedValues)
        {
            Console.WriteLine($"{pair.Key}: {pair.Value}");
        }
    }
}

在上面的示例中,我们首先依照字典的键进行排序,然后遍历输出键值对;然后依照字典的值进行排序,再次遍历输出键值对。你也能够根据具体的需求选择要排序的方式,比如依照键或值的升序或降序来排序。

tiktok粉丝购买:https://www.smmfensi.com/