Sorting a Dictionary in place with respect to keys

前端 未结 7 1256
广开言路
广开言路 2020-11-29 04:49

I have a dictionary in C# like

Dictionary

and I want to sort that dictionary in place with respect to keys (a f

7条回答
  •  迷失自我
    2020-11-29 05:32

    The correct answer is already stated (just use SortedDictionary).

    However, if by chance you have some need to retain your collection as Dictionary, it is possible to access the Dictionary keys in an ordered way, by, for example, ordering the keys in a List, then using this list to access the Dictionary. An example...

    Dictionary dupcheck = new Dictionary();
    

    ...some code that fills in "dupcheck", then...

    if (dupcheck.Count > 0) {
      Console.WriteLine("\ndupcheck (count: {0})\n----", dupcheck.Count);
      var keys_sorted = dupcheck.Keys.ToList();
        keys_sorted.Sort();
      foreach (var k in keys_sorted) {
        Console.WriteLine("{0} = {1}", k, dupcheck[k]);
      }
    }
    

    Don't forget using System.Linq; for this.

提交回复
热议问题