using System;
using System.Collections.Generic;
class Program
{
static void Main()
{
// 创建一个 Dictionary 并添加一些键值对
Dictionary<string, int> dictionary = new Dictionary<string, int>
{
{"apple", 1},
{"banana", 2},
{"cherry", 3},
{"date", 4}
};
// 按键排序
var sortedByKey = new SortedDictionary<string, int>(dictionary);
Console.WriteLine("Sorted by Key:");
foreach (var item in sortedByKey)
{
Console.WriteLine($"{item.Key}: {item.Value}");
}
// 按值排序
var sortedByValue = dictionary.OrderBy(pair => pair.Value).ToDictionary(pair => pair.Key, pair => pair.Value);
Console.WriteLine("\nSorted by Value:");
foreach (var item in sortedByValue)
{
Console.WriteLine($"{item.Key}: {item.Value}");
}
}
}
Dictionary<string, int> 并添加了一些键值对。SortedDictionary 可以直接按键进行排序。SortedDictionary 是一个有序的字典,它会根据键的自然顺序进行排序。OrderBy 方法可以按值进行排序。OrderBy 返回一个 IEnumerable<KeyValuePair<string, int>>,然后我们使用 ToDictionary 将其转换回字典。这段代码展示了如何按键和按值对 Dictionary 进行排序,并打印出排序后的结果。
上一篇:c# 位运算
下一篇:c# fileinfo
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站