C# Sort Dictionary

Sorted letters: A through Z

Dictionary has no Sort method. If we need to loop through the Dictionary contents in sorted order, we must separately acquire the elements and sort them. This is done with the Keys and Values properties and a List instance.

Sort keys

Note

This example solves the problem by using the Keys property on the Dictionary instance, and then the ToList extension method and the Sort instance method.

ToList Extension Method

First, an example Dictionary is created and populated with the Add method; next, the ToList and Sort methods are used on the Keys; finally, the resulting List is looped through using the foreach-loop construct. Also, please notice how the var implicit typed keyword is used throughout, to reduce syntactic redundancy.

Program that sorts keys in Dictionary [C#]

using System;
using System.Collections.Generic;
using System.Linq;

class Program
{
    static void Main()
    {
	// Create dictionary and add five keys and values.
	var dictionary = new Dictionary<string, int>();
	dictionary.Add("car", 2);
	dictionary.Add("apple", 1);
	dictionary.Add("zebra", 0);
	dictionary.Add("mouse", 5);
	dictionary.Add("year", 3);

	// Acquire keys and sort them.
	var list = dictionary.Keys.ToList();
	list.Sort();

	// Loop through keys.
	foreach (var key in list)
	{
	    Console.WriteLine("{0}: {1}", key, dictionary[key]);
	}
    }
}

Output

apple: 1
car: 2
mouse: 5
year: 3
zebra: 0

Sort values

Next we show how to sort the values in a Dictionary. We see a console program you can compile in Visual Studio and run. It adds keys to a Dictionary and then sorts them by their values. Remember that Dictionary instances are not initially sorted in any way. We use the LINQ orderby keyword in a query statement.

OrderBy Clause
Program that sorts Dictionary [C#]

using System;
using System.Collections.Generic;
using System.Linq;

class Program
{
    static void Main()
    {
	// 1.
	// Example dictionary.
	var d = new Dictionary<string, int>();
	d.Add("cat", 1);
	d.Add("dog", 0);
	d.Add("mouse", 5);
	d.Add("eel", 3);
	d.Add("programmer", 2);

	// 2.
	// Order by values.
	// Use LINQ to specify sorting by value.
	var items = from k in d.Keys
		    orderby d[k] ascending
		    select k;

	// 3.
	// Display results.
	foreach (string k in items)
	{
	    Console.WriteLine("{0}: {1}",
		k,
		d[k]);
	}
	// Pause.
	Console.Read();
    }
}

Output

dog: 0
cat: 1
programmer: 2
eel: 3
mouse: 5
Steps

Overview. First, it declares an example Dictionary. It contains keys in an arbitrary order. We will reorder them to go from lowest to highest value.

Using LINQ queries. It uses a LINQ query with the var keyword and accesses the Keys property of the Dictionary. Finally, it displays results, using foreach to iterate through and display the Dictionary. We do another lookup on each key.

LINQ Examples Var Examples

Result: The code works but it is not the absolute fastest solution. This is because it looks up values twice. It would be faster to develop a custom solution where the values are cached.

Notes

Warning

You will likely add more logic to the solution here for your project. The above console program could, with certain changes, raise a KeyNotFoundException. You will want to trap those errors with exception handling—try and catch.

Try Keyword Catch Examples

It is possible and quite easy to sort in the opposite direction as above. Simply replace the keyword 'ascending' with descending. When you omit the direction keyword entirely, it will use ascending. You can find more information on the descending contextual keyword.

Descending Keyword
Descending sort

var items = from k in d.Keys
	    orderby d[k] descending
	    select k;

Example output

mouse: 5
eel: 3
programmer: 2
cat: 1
dog: 0
Question and answer

Other methods I found involve more steps, more lines of code, or delegates and anonymous functions. What's wrong with those methods? Absolutely nothing, although they vary in efficiency. You may prefer this sort of home-grown solution.

Sort string values. Sorting strings would work just as well. What the runtime is doing is using the interface implementations of the types. So its syntax is exactly the same for strings, integers, decimals, or really any type that List.Sort() could sort.

IComparable Example With CompareTo

Summary

The C# programming language

A common theme in the Dictionary collection is immutability of its ordering. As a hashtable it is optimized for fast lookups, not for specific looping mechanisms. So while the Dictionary type is invaluable for lookup-heavy programs, it hinders programs that further demand certain enumeration patterns—such as sorted keys.

Dictionary Examples Sort Examples
.NET