C# Sort Dictionary Values
by Sam Allen - Updated January 14, 2010You want to sort your C# Dictionary by its values. The Dictionary has keys of any type, while the values can be sorted. Order the values so you can display your Dictionary or write it to disk. Here we see a simple method you can use to loop through your Dictionary in the order of its values, using the C# programming language.
Keys: dog cat programmer eel mouse Values: 0 [Sorted ascending] 1 2 3 5
Sorting Dictionary values
Here 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.
=== Example 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 of the program === dog: 0 cat: 1 programmer: 2 eel: 3 mouse: 5
Overview of steps in the example. 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.
Results of the example. The code works but it may not be 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. This article is based on .NET 3.5 SP1.
Sorting the opposite direction
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 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
Alternative methods for sorting
Other methods the author found on Google 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.
Sorting string values
In this section, we mention that 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.
Possible exceptions
Here, we note that 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/catch.
Summary
In this tutorial, we saw a simple query expression and loop that prints out the data in a Dictionary sorted by its values. It is not heavily optimized but is sufficient for many uses. Importantly, it is easily understood and simple for your reviewers to approve.