Dot Net Perls

Sort Dictionary Values - C#

by Sam Allen

Problem

Sort your C# Dictionary by its values. What you have is a Dictionary with string or any other type of keys and string or integer values. You want to order the values so you can display your Dictionary or write it to disk.

KeysSorted values
dog0
cat1
programmer2
eel3
mouse5

Solution: C#

My solution here is nearly the same as for my article where I sort strings by their lengths. What we use is the LINQ orderby keyword in a query statement. This allows us to specify that we want to order keys by their values. Then we iterate through the IEnumerable result.

Example code. The following code is 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 Dictionaries are not initially sorted in any way.)

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

class Program
{
    static void Main()
    {
        // 1.
        // Example dictionary
        Dictionary<string, int> 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] descending
                    select k;

        // 3.
        // Display results
        foreach (string k in items)
        {
            Console.Write(k);
            Console.Write(": ");
            Console.WriteLine(d[k]);
        }
        // Pause
        Console.Read();
    }
}
  1. Example Dictionary is declared.
    It contains keys in an arbitrary order. We will reorder them to go from lowest to highest value.
  2. LINQ query is used.
    Here we use the var keyword and access the Keys property of the Dictionary. Read morea about Dictionary keys and values.
  3. Results are displayed.
    This simple loop uses foreach to iterate through and display the Dictionary. We do another lookup on each key.

So does it work?

Yes, 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. Here's the output.

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

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. You can omit the direction keyword entirely and it will use ascending.

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

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

So, what other ways are there?

Other methods I 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. I like my home-grown solution.

What about strings?

Strings would work just as well. What C# 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.

Can any exceptions be raised?

Yes. From my inspection I see that the above console program could, with certain changes, raise a KeyNotFoundException. You will want to trap those errors with exception handling (try/catch). The LINQ statement looks fairly safe to me.

What else should I note?

Look at the pattern I use for writing the strings to the console. I use separate statements for each part. My research shows that this is much faster than using string concatenation. (This isn't really the focus of the article.)

Summary

Use this LINQ method in C# to sort a Dictionary by its values. It uses the LINQ query syntax to make the code more elegant than many other methods with delegates. It is easily understood and simple for your reviewers to approve. Read many more articles about Dictionary.

Dot Net Perls
About
Sitemap
Source code
RSS
Dictionary
Dictionary Keys and Values
Dictionary Lookup Methods
Sort Dictionary Values
Dictionary vs. List Lookup Time
ToDictionary Use
Recent
Pi
NGEN Installer Class
List Element Equality
DateTime Tips and Tricks
Remove HTML Tags From String
© 2008 Sam Allen. All rights reserved.