【问题标题】:C# string Dictionary sortingC# 字符串字典排序
【发布时间】:2016-03-04 18:43:39
【问题描述】:

我想按键对下面的字典进行排序。

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 代替吗? msdn.microsoft.com/en-us/library/f7fta44c(v=vs.110).aspx
  • 如果我使用 SortedDictionary 。我的输出是 (1,+1)(100,+100)(24,+24)(214,+214)(3,+3)
  • 你有想过 LINQ 吗?
  • 为了完整起见,排序字典不起作用的原因是因为您有一个字符串作为键值。排序顺序对于字符串排序是正确的。通过使用@gaemaf 答案,您表明该键可以是一个 int 值。您最好的做法是将 Numbers 更改为 Numbers 并让键在任何地方都是整数。只是为了迂腐,带有字符串键的排序字典结果是 (1, +1)(100, +100)(214, +214)(24, +24)(3, +3)

标签: c# dictionary


【解决方案1】:

字典类型本质上是无序的,但您可以改用SortedDictionary。

类似的问题在这里得到了更详细的回答:https://stackoverflow.com/a/2705623/2608569

【讨论】:

    【解决方案2】:

    您可以使用 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"}};
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-10-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-05-29
      • 2016-09-10
      • 1970-01-01
      相关资源
      最近更新 更多