C# Sort Dictionary
Sorted letters: A to 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.
DictionaryList
Example
Dictionary
This example solves the problem by using the Keys property on the Dictionary instance. Then it uses the ToList extension method and the Sort instance method. An example Dictionary is created and populated with the Add method.
Next:The ToList and Sort methods are used on the Keys. The resulting List is looped through using the foreach-loop construct.
ToListForeach
Note: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
Example 2
KeyValuePair: Key and Value properties
Next we show how to sort the values in a Dictionary. This program adds keys to a Dictionary and then sorts them by their values. Dictionary instances are not initially sorted in any way. We use the 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()
{
// Example dictionary.
var dictionary = new Dictionary<string, int>(5);
dictionary.Add("cat", 1);
dictionary.Add("dog", 0);
dictionary.Add("mouse", 5);
dictionary.Add("eel", 3);
dictionary.Add("programmer", 2);
// Order by values.
// ... Use LINQ to specify sorting by value.
var items = from pair in dictionary
orderby pair.Value ascending
select pair;
// Display results.
foreach (KeyValuePair<string, int> pair in items)
{
Console.WriteLine("{0}: {1}", pair.Key, pair.Value);
}
// Reverse sort.
// ... Can be looped over in the same way as above.
items = from pair in dictionary
orderby pair.Value descending
select pair;
}
}
Output
dog: 0
cat: 1
programmer: 2
eel: 3
mouse: 5
Steps
First, it declares an example Dictionary. It contains keys in an arbitrary order. The Dictionary keys are strings. Its values are ints. We will reorder the values to go from lowest to highest.
It uses a LINQ query with the var keyword and accesses the KeyValuePairs from the Dictionary. It finally displays results, using foreach to iterate through and display each KeyValuePair. No additional lookups are required.
LINQVarKeyValuePair
Note:Thanks to Jon Senchyna for improving the query expression. It is more efficient to use the collection of KeyValuePairs.
OrderBy
Lambda expression syntax
Another option is the OrderBy extension method in System.Linq. This approach compiles to the same code as the orderby query expression. But the syntax is shorter. It requires only one lambda expression and method call.
Lambda
Program that uses OrderBy method: C#
using System;
using System.Collections.Generic;
using System.Linq;
class Program
{
static void Main()
{
var items = new Dictionary<int, int>();
items.Add(-1, 0);
items.Add(0, 1);
items.Add(-2, 0);
items.Add(3, 1);
// Use OrderBy method.
foreach (var item in items.OrderBy(i => i.Key))
{
Console.WriteLine(item);
}
}
}
Output
[-2, 0]
[-1, 0]
[0, 1]
[3, 1]
Note:Thanks to Even Holen for writing in with an example of the shorter OrderBy syntax form.
Discussion
Warning: exclamation mark
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\u2014try and catch.
TryCatch
It is possible and easy to sort in the opposite direction. Simply replace the keyword ascending with descending. When you omit the direction keyword entirely, it will use ascending. You can find more information on descending.
Descending
Descending sort
var items = from pair in dictionary
orderby pair.Value descending
select pair;
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. There is nothing wrong with those methods, 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. Its syntax is the same for any type that List.Sort() could sort.
IComparable
Summary
As a hashtable, Dictionary is optimized for fast lookups, not for specific looping mechanisms. So while Dictionary is invaluable for lookup-heavy programs, it hinders programs that demand certain enumeration patterns\u2014such as sorted keys.
C#: Sort