Home
Search
Sort Dictionary: Keys and ValuesSort the keys and values in a Dictionary with orderby and query expressions.
C#
This page was last reviewed on Nov 17, 2022.
Sort Dictionary. 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.
Sort
Shows a dictionary
Sorting approaches. We can sort a Dictionary with the Keys and Values properties and a List instance. Some approaches are slower than others.
An example. To begin, we sort the string keys in a Dictionary. In the output, the string "apple" should come before the string "zebra."
Step 1 An example Dictionary is created. The var implicit typed keyword is used to reduce syntactic redundancy.
Var
Step 2 We access the Keys property. Then we use the ToList extension method and the Sort instance method.
ToList
Step 3 The resulting List is looped through using the foreach-loop construct. We print each key and its value.
List
Foreach
Shows a dictionary
using System; using System.Collections.Generic; using System.Linq; class Program { static void Main() { // Step 1: create dictionary. var dictionary = new Dictionary<string, int>(); dictionary.Add("car", 2); dictionary.Add("zebra", 0); dictionary.Add("apple", 1); // Step 2: get keys and sort them. var list = dictionary.Keys.ToList(); list.Sort(); // Step 3: loop through keys. foreach (var key in list) { Console.WriteLine("{0}: {1}", key, dictionary[key]); } } }
apple: 1 car: 2 zebra: 0
Sort values. This program adds keys to a Dictionary and then sorts them by their values. Dictionary instances are not initially sorted. We use the orderby keyword in a query statement.
orderby
Example The dictionary has string keys, and int values. We will reorder the values to go from lowest to highest.
Query It displays results, using foreach to iterate through and display each KeyValuePair. No additional lookups are required.
KeyValuePair
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; } }
dog: 0 cat: 1 programmer: 2 eel: 3 mouse: 5
OrderBy. Another option is the OrderBy extension method in System.Linq. This approach compiles to the same code as the orderby query expression.
Tip Here the syntax is shorter. It requires only one lambda expression and method call.
Lambda
Exceptions The program could (with certain changes) raise a KeyNotFoundException. We can trap those errors with exception handling.
Exception
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); } } }
[-2, 0] [-1, 0] [0, 1] [3, 1]
Tip, opposite direction. It is possible and easy to sort in the opposite direction. Replace ascending with descending. When you omit the direction keyword, it will use ascending.
Descending
Descending sort:
var items = from pair in dictionary orderby pair.Value descending select pair;
mouse: 5 eel: 3 programmer: 2 cat: 1 dog: 0
Notes, other methods. Other methods I found involve more steps, code or complexity. There is nothing wrong with those methods, although they vary in efficiency.
Sort string values. Sorting strings would work just as well. Sort() uses the interface implementations of the types. Its syntax is the same for any type that List.Sort() could sort.
IComparable
A summary. Dictionary is optimized for fast lookups, not for specific looping mechanisms. It helps in lookup-heavy programs, but hinders programs that require sorted keys.
Dictionary
Dot Net Perls is a collection of tested code examples. Pages are continually updated to stay current, with code correctness a top priority.
Sam Allen is passionate about computer languages. In the past, his work has been recommended by Apple and Microsoft and he has studied computers at a selective university in the United States.
This page was last updated on Nov 17, 2022 (simplify).
Home
Changes
© 2007-2023 Sam Allen.