【问题标题】:How to sort a dictionary by key如何按键对字典进行排序
【发布时间】:2011-11-13 07:45:55
【问题描述】:

我有字典Dictionary<string, Point>

键是 c1,c3,c2,t1,,t4,t2 我想将它们排序为 c1,c2,c3,t1,t2,t3

我正在尝试使用它对其进行排序

Input.OrderBy(key => key.Key );

但它不起作用

知道如何解决这个问题

【问题讨论】:

标签: c# .net linq dictionary


【解决方案1】:

Input.OrderBy 不对字典进行排序,它会创建一个查询,以特定顺序返回项目。

也许OrderedDictionary 会给你你想要的。

或者使用通用SortedDictionary

【讨论】:

  • @AMH 在实际测试之前不要对性能做出假设(微基准不计算在内)。
  • 另一种情况,人们来到这里寻找的实际答案低于“正确”答案,该答案被低估为 0 以下,并且 cmets 争论不相关的考虑。
【解决方案2】:

将未排序的对象加载到 SortedDictionary 对象中,如下所示:

SortedDictionary<string, string> sortedCustomerData = new SortedDictionary<string,string>(unsortedCustomerData);

其中 unsortedCustomerData 是相同的泛型类型(字典字符串、字符串或在您的情况下为字符串、点)。它会自动按键排序新对象

根据 msdn:SortedDictionary(IDictionary):初始化 SortedDictionary 类的新实例,该类包含从指定 IDictionary 复制的元素,并为键类型使用默认的 IComparer 实现。

【讨论】:

  • 可能旧了,但是谢谢,工作得很好,而且只有一个班轮。
【解决方案3】:

由于 Input.OrderBy 创建了一个以有序顺序返回项目的查询,因此只需将其分配给同一个字典。

objectDict = objectDict.OrderBy(obj =&gt; obj.Key).ToDictionary(obj =&gt; obj.Key, obj =&gt; obj.Value);

【讨论】:

    【解决方案4】:

    只是一个猜测,但看起来您假设它将对输入进行排序。 OrderBy 方法实际上返回包含相同值的 IOrderedEnumerable 的有序实例。如果要保留返回值,可以执行以下操作:

    IOrderedEnumerable orderedInput
    orderedInput = Input.OrderBy(key=>key.Key)
    

    大多数修改集合的方法都遵循同样的模式。它这样做是为了不更改原始集合实例。这可以防止您在不打算更改实例时意外更改实例。如果您确实只想使用排序后的实例,那么您只需将变量设置为方法的返回值,如上所示。

    【讨论】:

      【解决方案5】:

      以下代码使用两个lists 到sort 一个字典。

      using System;
      using System.Collections.Generic;
      using System.Drawing;
      
      namespace ConsoleApplication1 {
          class Program {
              static void Main(string[] args) {
                  Dictionary<string,Point> r=new Dictionary<string,Point>();
                  r.Add("c3",new Point(0,1));
                  r.Add("c1",new Point(1,2));
                  r.Add("t3",new Point(2,3));
                  r.Add("c4",new Point(3,4));
                  r.Add("c2",new Point(4,5));
                  r.Add("t1",new Point(5,6));
                  r.Add("t2",new Point(6,7));
                  // Create a list of keys
                  List<string> zlk=new List<string>(r.Keys);
                  // and then sort it.
                  zlk.Sort();
                  List<Point> zlv=new List<Point>();
                  // Readd with the order.
                  foreach(var item in zlk) {
                      zlv.Add(r[item]);
                  }
                  r.Clear();
                  for(int i=0;i<zlk.Count;i++) {
                      r[zlk[i]]=zlv[i];
                  }
                  // test output
                  foreach(var item in r.Keys) {
                      Console.WriteLine(item+" "+r[item].X+" "+r[item].Y);
                  }
                  Console.ReadKey(true);
              }
          }
      }
      

      上面代码的输出如下所示。

      c1 1 2
      c2 4 5
      c3 0 1
      c4 3 4
      t1 5 6
      t2 6 7
      t3 2 3
      

      【讨论】:

        【解决方案6】:

        我用过

        var l =  Input.OrderBy(key => key.Key);
        

        我把它转换成字典

        【讨论】:

        • 我说过:这不会对字典进行排序!它创建一个排序的“视图”。
        【解决方案7】:

        好的,检查一下它应该可以工作

        var r = new Dictionary<string, Point>();
        r.Add("c3", new Point(0, 0));
        r.Add("c1", new Point(0, 0));
        r.Add("t3", new Point(0, 0));
        r.Add("c4", new Point(0, 0));
        r.Add("c2", new Point(0, 0));
        r.Add("t1", new Point(0, 0));
        r.Add("t2", new Point(0, 0));
        var l = r.OrderBy(key => key.Key);
        var dic = l.ToDictionary((keyItem) => keyItem.Key, (valueItem) => valueItem.Value);
        
        foreach (var item in dic)
        {
        
            Console.WriteLine(item.Key);
        }
        Console.ReadLine();
        

        【讨论】:

        • -1:这行不通。您刚刚创建了另一个没有排序的字典。它可能适用于小型词典,但最终会失败。
        • 我们在聊天中谈过,我知道他想要什么,所以我帮他解决了他的问题
        • @DeveloperX - 我的猜测是人们投票反对,因为它没有回答问题。我们看不到聊天,因此人们可能不认为它是对我们看到的问题的有用答案。
        猜你喜欢
        • 2012-02-18
        • 1970-01-01
        • 2021-08-20
        • 2013-03-14
        • 1970-01-01
        • 2014-04-11
        • 2021-12-20
        相关资源
        最近更新 更多