c#

C#如何对字典进行逆序排序

小樊
87
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
看了该问题的人还看了