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

   2024-10-06 6110
核心提示:可以通过使用LINQ来对字典进行逆序排序。以下是一个示例代码:using System;using System.Collections.Generic;using System.Lin

可以通过使用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方法对字典按值进行逆序排序,并将结果转换为新的字典。最后通过遍历打印排序后的字典。

 
举报打赏
 
更多>同类物流大全
推荐图文
推荐物流大全
点击排行

网站首页  |  关于我们  |  联系方式 | 网站留言    |  赣ICP备2021007278号