【问题标题】:How to sort Dictionary on keys in c# [duplicate]如何在c#中对字典进行排序[重复]
【发布时间】: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 =&gt; e.Key))

标签: c# .net sorting dictionary


【解决方案1】:
var dict = new Dictionary<int, string>(){
  {1, "a"},
  {3, "c"},
  {2, "b"}
};

foreach (var k in dict.OrderByDescending(x => x.Key))
{
   Console.WriteLine(k);
}

【讨论】:

  • 是的,但是如何将System.Linq.IOrderedEnumerable&lt;System.Collections.Generic.KeyValuePair&lt;int, string&gt;&gt; 转换回Dictionary
  • 你不能不丢失排序。字典未排序。
猜你喜欢
  • 2015-12-18
  • 2015-12-26
  • 1970-01-01
  • 2015-11-03
  • 1970-01-01
  • 2010-10-09
  • 2021-11-29
相关资源
最近更新 更多