Coder Perfect

What is the best way to sort a dictionary by value?


By value, a dictionary made up of keys and values. For example, I have a hash of terms and their corresponding frequencies that I’d like to sort by frequency.

I have a SortedList that is good for a single variable (for example, frequency), and I’d like to map it back to the word.

SortedDictionary sorts by key rather than value. Some people resort to creating their own class, but is there a better way?

Asked by Kalid

Solution #1


Dictionary<string, int> myDict = new Dictionary<string, int>();
myDict.Add("one", 1);
myDict.Add("four", 4);
myDict.Add("two", 2);
myDict.Add("three", 3);

var sortedDict = from entry in myDict orderby entry.Value ascending select entry;

This would also provide you a lot of versatility because you could choose the top 10, 20, 10%, and so on. You may also use the StartsWith clause if you’re utilizing your word frequency index for type-ahead.

Answered by caryden

Solution #2


using System.Linq.Enumerable;
List<KeyValuePair<string, string>> myList = aDictionary.ToList();

    delegate(KeyValuePair<string, string> pair1,
    KeyValuePair<string, string> pair2)
        return pair1.Value.CompareTo(pair2.Value);

Because you’re targeting.NET 2.0 or higher, you can convert this to lambda syntax, which is similar but shorter. If you’re targeting.NET 2.0, you can only use this syntax using the Visual Studio 2008 compiler (or above).

var myList = aDictionary.ToList();

myList.Sort((pair1,pair2) => pair1.Value.CompareTo(pair2.Value));

Answered by Leon Bambrick

Solution #3

You could use:

var ordered = dict.OrderBy(x => x.Value).ToDictionary(x => x.Key, x => x.Value);

Answered by sean

Solution #4

We can do this by looking about and leveraging various C# 3.0 features:

foreach (KeyValuePair<string,int> item in keywordCounts.OrderBy(key=> key.Value))
    // do something with item.Key and item.Value

This is the cleanest solution I’ve seen, and it’s similar to Ruby’s approach to hashes.

Answered by Kalid

Solution #5

You can sort a Dictionary by value and save it back to itself (such that the values appear in order when you foreach over it):

dict = dict.OrderBy(x => x.Value).ToDictionary(x => x.Key, x => x.Value);

Sure, it’s not perfect, but it gets the job done.

Answered by Matt Frear

Post is based on