C#排序字典教程展示了如何使用C#语言对字典元素进行排序。C#教程是C#语言的综合教程。
排序
在编程中,排序意味着按有序顺序排列元素。多年来,开发了多种算法来对数据进行排序,包括归并排序、快速排序、选择排序或冒泡排序。
与排序相反,以随机或无意义的顺序重新排列元素序列,称为洗牌。我们可以按字母顺序或数字顺序对数据进行排序。排序键指定用于执行排序的条件。
C#具有用于高效排序数据的内置方法。
C#按值排序字典
下面的例子,我们对一个小字典进行排序。
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
在下一个示例中,我们使用查询表达式语法。
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#字典按键排序
接下来,我们按键对字典进行排序。
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表示按键排序的键/值对的集合。
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#语言中的Dictionary元素进行了排序。
列出所有C#教程。
