Home » c# » Sorting a Dictionary in place with respect to keys

Sorting a Dictionary in place with respect to keys

Posted by: admin November 30, 2017 Leave a comment

Questions:

I have a dictionary in C# like

Dictionary<Person, int>

and I want to sort that dictionary in place with respect to keys (a field in class Person). How can I do it? Every available help on the internet is that of lists with no particular example of in place sorting of Dictionary. Any help would be highly appreciated!

Answers:

You can’t sort a Dictionary<TKey, TValue> – it’s inherently unordered. (Or rather, the order in which entries are retrieved is implementation-specific. You shouldn’t rely on it working the same way between versions, as ordering isn’t part of its designed functionality.)

You can use SortedList<TKey, TValue> or SortedDictionary<TKey, TValue>, both of which sort by the key (in a configurable way, if you pass an IEqualityComparer<T> into the constructor) – might those be of use to you?

Pay little attention to the word “list” in the name SortedList – it’s still a dictionary in that it maps keys to values. It’s implemented using a list internally, effectively – so instead of looking up by hash code, it does a binary search. SortedDictionary is similarly based on binary searches, but via a tree instead of a list.

Questions:
Answers:

Try using SortedDictionary

Questions:
Answers:

By design, dictionaries are not sortable. If you need this capability in a dictionary, look at SortedDictionary instead.

Questions:
Answers:

Take a look at SortedDictionary, there’s even a constructor overload so you can pass in your own IComparable for the comparisons.

Questions:
Answers:

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<string, int> dupcheck = new Dictionary<string, int>();

…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.

Questions:
Answers:

While Dictionary is implemented as a hash table, SortedDictionary is implemented as a Red-Black Tree.

If you don’t take advantage of the order in your algorithm and only need to sort the data before output, using SortedDictionary would have negative impact on performance.

You can “sort” the dictionary like this:

Dictionary<string, int> dictionary = new Dictionary<string, int>();
// algorithm
return new SortedDictionary<string, int>(dictionary);