C# string Dictionary sorting
我想在字典下面按关键字排序。
1 | Dictionary<string, string> Numbers; |
样本数据:
1 2 3 4 5 | (100,+100) (24,+24) (214,+214) (3,+3) (1,+1) |
号
预期输出:
1 2 3 4 5 | (1,+1) (3,+3) (24,+24) (100,+100) (214,+214) |
如果使用SortedDictionary,则输出为
(1,+1)(100,+100)(24,+24)(214,+214)(3,+3)
可以使用SortedDictionary,但需要重新排列输入或保留类型:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | 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