溫馨提示×

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

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

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

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

class Program
{
    static void Main()
    {
        // 創建一個字典
        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);
        }
    }
}

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

0
亚洲午夜精品一区二区_中文无码日韩欧免_久久香蕉精品视频_欧美主播一区二区三区美女