C#字符串字典排序
本文关键字:排序 字典 字符串 | 更新日期: 2023-09-27 18:25:11
我想按关键字对下面的dictionary进行排序。
Dictionary<string, string> Numbers;
样本数据:
(100,+100)
(24,+24)
(214,+214)
(3,+3)
(1,+1)
预期输出:
(1,+1)
(3,+3)
(24,+24)
(100,+100)
(214,+214)
如果我使用SortedDictionary,我的输出是
(1,+1)(100,+100)(24,+24)(214,+214)(3,+3)
您可以使用SortedDictionary,但需要重新排列输入或保留类型:
Dictionary<string, string> Numbers = new Dictionary<string, string> {
{"100","+100"},
{"24","+24"},
{"214","+214"},
{"3","+3"},
{"1","+1"}};
Numbers = Numbers.OrderBy(key => int.Parse(key.Key)).ToDictionary((keyItem) => keyItem.Key, (valueItem) => valueItem.Value);
SortedDictionary<int, string> Numbers1 = new SortedDictionary<int, string> {
{100,"+100"},
{24,"+24"},
{214,"+214"},
{3,"+3"},
{1,"+1"}};
字典类型本质上是无序的,但您可以使用SortedDictionary。
类似的问题在这里得到了更详细的回答:https://stackoverflow.com/a/2705623/2608569