【发布时间】:2021-02-17 08:01:36
【问题描述】:
我有一个字典,我想按它的键排序。
var dict = new Dictionary<int, string>(){
{1, "a"},
{3, "c"},
{2, "b"}
};
单独将其转换为 SortedDictionary 是行不通的,因为我需要将键的值降序:
var sortedDict = new SortedDictionary<int, string>(dict);
foreach (var k in sortedDict)
{
Console.WriteLine(k);
}
// Result:
[1, a]
[2, b]
[3, c]
// Desired result:
[3, c]
[2, b]
[1, a]
有没有办法使用自定义排序选项(如 lambda)对 Dictionary 进行排序?
【问题讨论】:
-
SortedDictionary 有一个构造函数,您可以在其中传入一个 IComparer
,它应该允许您随意排序。 -
foreach (var kvp in dict.OrderByDescending(e => e.Key))
标签: c# .net sorting dictionary