C#字典的键值对如何排序
导读:在C#中,字典(Dictionary)是一种无序的集合,它不保证元素的顺序。如果你需要对字典的键值对进行排序,可以使用以下方法: 使用OrderBy和ThenBy方法对字典进行排序: using System; using System...
在C#中,字典(Dictionary)是一种无序的集合,它不保证元素的顺序。如果你需要对字典的键值对进行排序,可以使用以下方法:
- 使用
OrderBy和ThenBy方法对字典进行排序:
using System;
using System.Collections.Generic;
using System.Linq;
class Program
{
static void Main()
{
Dictionary<
string, int>
dict = new Dictionary<
string, int>
{
{
"apple", 5}
,
{
"banana", 3}
,
{
"orange", 7}
,
{
"grape", 2}
}
;
// 按键(Key)排序
var sortedByKey = dict.OrderBy(x =>
x.Key);
// 按值(Value)排序
var sortedByValue = dict.OrderBy(x =>
x.Value);
Console.WriteLine("Sorted by Key:");
foreach (var item in sortedByKey)
{
Console.WriteLine($"{
item.Key}
: {
item.Value}
");
}
Console.WriteLine("\nSorted by Value:");
foreach (var item in sortedByValue)
{
Console.WriteLine($"{
item.Key}
: {
item.Value}
");
}
}
}
- 将字典转换为有序集合,例如
SortedDictionary或SortedList:
using System;
using System.Collections.Generic;
class Program
{
static void Main()
{
Dictionary<
string, int>
dict = new Dictionary<
string, int>
{
{
"apple", 5}
,
{
"banana", 3}
,
{
"orange", 7}
,
{
"grape", 2}
}
;
// 使用 SortedDictionary 对键进行排序
SortedDictionary<
string, int>
sortedDictByKey = new SortedDictionary<
string, int>
(dict);
// 使用 SortedList 对值进行排序
SortedList<
int, string>
sortedListByValue = new SortedList<
int, string>
();
foreach (var item in dict)
{
sortedListByValue.Add(item.Value, item.Key);
}
Console.WriteLine("Sorted by Key using SortedDictionary:");
foreach (var item in sortedDictByKey)
{
Console.WriteLine($"{
item.Key}
: {
item.Value}
");
}
Console.WriteLine("\nSorted by Value using SortedList:");
foreach (var item in sortedListByValue)
{
Console.WriteLine($"{
item.Value}
: {
item.Key}
");
}
}
}
请注意,这些方法会创建新的集合,而不是修改原始字典。如果你需要保留原始字典的顺序,可以使用这些方法之一。如果你不关心原始字典的顺序,可以直接对其进行排序。
声明:本文内容由网友自发贡献,本站不承担相应法律责任。对本内容有异议或投诉,请联系2913721942#qq.com核实处理,我们将尽快回复您,谢谢合作!
若转载请注明出处: C#字典的键值对如何排序
本文地址: https://pptw.com/jishu/698569.html
