C# 排序字典
最后修改于 2023 年 7 月 5 日
C# 排序字典教程展示了如何在 C# 语言中排序字典元素。
排序
在编程中,排序意味着将元素排列成有序序列。多年来,已经开发了几种算法来对数据进行排序,包括归并排序、快速排序、选择排序或冒泡排序。
排序的反面,即以随机或无意义的顺序重新排列元素序列,称为洗牌。我们可以按字母或数字对数据进行排序。排序键指定用于执行排序的标准。
C# 具有内置方法,可用于高效地对数据进行排序。
C# 按值排序字典
以下示例,我们排序一个小型字典。
Program.cs
var users = new Dictionary<string, int>() { { "John", 41 }, { "Jane", 38 }, { "Lucy", 29 }, { "Paul", 24 } }; var sorted = users.OrderBy(user => user.Value); foreach (var user in sorted) { Console.WriteLine($"{user.Key} is {user.Value} years old"); } Console.WriteLine("----------------------------"); var sorted2 = users.OrderByDescending(user => user.Value); foreach (var user in sorted2) { Console.WriteLine($"{user.Key} is {user.Value} years old"); }
使用 OrderBy
和 OrderByDescending
方法,我们按其值的升序和降序对字典进行排序。
$ dotnet run Paul is 24 years old Lucy is 29 years old Jane is 38 years old John is 41 years old ---------------------------- John is 41 years old Jane is 38 years old Lucy is 29 years old Paul is 24 years old
在下一个示例中,我们使用查询表达式语法。
Program.cs
var users = new Dictionary<string, int>() { { "John", 41 }, { "Jane", 38 }, { "Lucy", 29 }, { "Paul", 24 } }; var sorted = from pair in users orderby pair.Value select pair; foreach (var user in sorted) { Console.WriteLine($"{user.Key} is {user.Value} years old"); } Console.WriteLine("------------------------"); var sorted2 = from pair in users orderby pair.Value descending select pair; foreach (var user in sorted2) { Console.WriteLine($"{user.Key} is {user.Value} years old"); }
该示例使用 LINQ 查询表达式语法按其值的升序和降序对字典的元素进行排序。
C# 按键排序字典
接下来,我们按键排序字典。
Program.cs
var users = new Dictionary<string, int>() { { "John", 41 }, { "Jane", 38 }, { "Lucy", 29 }, { "Paul", 24 } }; var sorted = users.OrderBy(user => user.Key); foreach (var user in sorted) { Console.WriteLine($"{user.Key} is {user.Value} years old"); } Console.WriteLine("----------------------------"); var sorted2 = users.OrderByDescending(user => user.Key); foreach (var user in sorted2) { Console.WriteLine($"{user.Key} is {user.Value} years old"); }
该示例使用 OrderBy
和 OrderByDescending
方法按其键的升序和降序对字典元素进行排序。
$ dotnet run Jane is 38 years old John is 41 years old Lucy is 29 years old Paul is 24 years old ---------------------------- Paul is 24 years old Lucy is 29 years old John is 41 years old Jane is 38 years old
C# SortedDictionary
SortedDictionary
表示一个基于键排序的键/值对的集合。
Program.cs
var sortedUsers = new SortedDictionary<string, int>() { { "John", 41 }, { "Jane", 38 }, { "Lucy", 29 }, { "Paul", 24 } }; foreach (var user in sortedUsers) { Console.WriteLine($"{user.Key} is {user.Value} years old"); }
该示例演示了 SortedDictionary
的用法。
来源
在本文中,我们对 C# 语言中的字典元素进行了排序。
作者
列出所有 C# 教程。