Sorting a Dictionary on a List of Keys

Kees C. Bakker
Oct 13, 2018 · 2 min read

I can almost hear you thinking: “What super-weird problem are you trying to solve!?” Well… it is kind of an abstract one! Imagine you have a dictionary of objects and a separate list of keys in a certain order. Now suppose you want an ordered dictionary based on the list of keys.

We have a dictionary with objects with the color as key.
Now we would like to sort the objects in the same order as the list of colors.
Note: not all colors are in the list.

According to the documentation the order of the generic Dictionary<TKey, TValue> is not guaranteed. When I tested the order, it looked like it was the same as the insertion order. If you need a sorted dictionary the SortedDictionary<TKey, TValue> is your man.

Building a KeyComparer

So we basically need to influence the sorting-mechanism of the SortedDictionary. This can be done by implementing an IComparer that will do the sorting based on the list of keys. We should adhere to the following rules:

  • The position of each key in the list should determine the position in the sorted dictionary.
  • If a key has a lower position in the list, the position in the dictionary should be lower as well.
  • If a key is not in the list, just put it on the bottom of the dictionary.

Converted into code, it will look like this.

Implementing the comparer can be quite confusing (it was for me). Fortunately there is documentation. To make things less confusing I used constants instead of integers. Another trick is to make the first parameter the “hero” and think of the compare as deciding if our hero should go to the TOP or BOTTOM of the sorted dictionary.

The result

Now let’s compare what happens if we insert a few values in a normal dictionary versus a sorted dictionary (with the new sorter and a list of fields to sort on):

Getting some extensions

I love Linq and it feels like this sorting-feature should be a Linq-like extension as well:

So that’s it, we can sort. The world has order again.

Originally published at on October 13, 2018.


We'll try to keep up and post on the stuff we're doing and discovering. Interesting in working @wehkamp? Check out

Kees C. Bakker

Written by

I work as a Lead Developer for one of the biggest web-shops in the Netherlands: wehkamp. I ❤️ C# and I like to solve nifty problems.


We'll try to keep up and post on the stuff we're doing and discovering. Interesting in working @wehkamp? Check out

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade