溫馨提示×

C#如何對字典進行逆序排序

c#
小樊
87
2024-07-15 10:43:35
欄目: 編程語言

可以通過使用LINQ來對字典進行逆序排序。以下是一個示例代碼:

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

class Program
{
    static void Main()
    {
        // 創(chuàng)建一個字典
        Dictionary<string, int> dict = new Dictionary<string, int>();
        dict.Add("Apple", 5);
        dict.Add("Banana", 3);
        dict.Add("Orange", 7);

        // 使用LINQ對字典進行逆序排序
        var sortedDict = dict.OrderByDescending(x => x.Value).ToDictionary(x => x.Key, x => x.Value);

        // 打印排序后的字典
        foreach (var item in sortedDict)
        {
            Console.WriteLine("{0}: {1}", item.Key, item.Value);
        }
    }
}

在上面的示例中,首先創(chuàng)建了一個包含字符串鍵和整數(shù)值的字典。然后使用LINQ的OrderByDescending方法對字典按值進行逆序排序,并將結(jié)果轉(zhuǎn)換為新的字典。最后通過遍歷打印排序后的字典。

0