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.
| Keys | Sorted values |
| dog | 0 |
| cat | 1 |
| programmer | 2 |
| eel | 3 |
| mouse | 5 |
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();
}
}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
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: 0Other 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.
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.
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.
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.)
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.