An example list dictionary of keys and values, showing how the dictionary can be sorted according to the keys

C#: Sort dictionary by key

How to sort dictionary by key in C#, and return a sorted list of values.

Let’s say you have some values. Each value is associated with a string, called a key. We want to sort the values such that their corresponding keys are in order.

c# sort dictionary by key

The basic idea is that we want to sort our keys, and then look up the dictionary according to the sorted keys.

But we have to be careful – we need to sort the keys without damaging the original dictionary. A good solution is to create a copy of the keys before you sort them.

See below for a full example:

Option 1: C# code to sort dictionary by key

  public List<object> SortDictionary()
  {
    //Create the data we want to sort.
    //In the data below, we are saying that "B corresponds to 21", "F corresponds to 43" and so on.
    //Normally, you would probably be feeding this data from somewhere else in your program.
    List<string> Keys = new List<string>();
    List<object> Values = new List<object>();
    Keys.Add("B");
    Keys.Add("F");
    Keys.Add("A");
    Keys.Add("D");
    Keys.Add("C");
    Keys.Add("E");
    Values.Add(21);
    Values.Add(43);
    Values.Add(6);
    Values.Add(54);
    Values.Add(65);
    Values.Add(3);

    //Declare new dictionary, where the key is a string and the corresponding data is an object
    var dict = new Dictionary<string, object>();
    //populate dictionary with data created above
    for (int i = 0; i < Keys.Count; i++) dict.Add(Keys[i], Values[i]);

    //Separately, sort our keys into alphabetical order
    //You need your keys in their own list. You may need to create this yourself if you don't already have it.
    Keys.Sort();

    //Now look up our dictionary according to our sorted keys
    List<object> sortedVals = new List<object>();
    for (int i = 0; i < Keys.Count; i++)
    {
      sortedVals.Add(dict[Keys[i]]);
    }
    return sortedVals;
  }

Thanks to Fraser Greenroyd for helping me with the code snippet above.

Option 2: Use SortedDictionary to sort a dictionary in C#

If you require that your dictionary is always going to be sorted, it might be better to use a SortedDictionary rather than just a Dictionary.

Whenever you add an item to a SortedDictionary, the item will be inserted into the correct location.

Note that there is a performance penalty for some SortedDictionary operations, so you should consider whether a SortedDictionary is best for you.

    var sdict = new SortedDictionary<string, object>();
    for (int i = 0; i < Keys.Count; i++) sdict.Add(Keys[i], Values[i]);
    return sdict.Values.ToList();

One thought on “C#: Sort dictionary by key”

Leave a Reply

Your email address will not be published.

Time limit is exhausted. Please reload CAPTCHA.

This site uses Akismet to reduce spam. Learn how your comment data is processed.

%d bloggers like this: