HiveBrain v1.2.0
Get Started
← Back to all entries
snippetcsharpCritical

How do you sort a dictionary by value?

Submitted by: @import:stackoverflow-api··
0
Viewed 0 times
youhowsortdictionaryvalue

Problem

I often have to sort a dictionary (consisting of keys & values) by value. For example, I have a hash of words and respective frequencies that I want to order by frequency.

There is a SortedList which is good for a single value (say frequency), that I want to map back to the word.

SortedDictionary orders by key, not value. Some resort to a custom class, but is there a cleaner way?

Solution

Use:

using System.Linq.Enumerable;
...
List> myList = aDictionary.ToList();

myList.Sort(
    delegate(KeyValuePair pair1,
    KeyValuePair pair2)
    {
        return pair1.Value.CompareTo(pair2.Value);
    }
);


Since you're targeting .NET 2.0 or above, you can simplify this into lambda syntax -- it's equivalent, but shorter. If you're targeting .NET 2.0 you can only use this syntax if you're using the compiler from Visual Studio 2008 (or above).

var myList = aDictionary.ToList();

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

Code Snippets

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

myList.Sort(
    delegate(KeyValuePair<string, string> pair1,
    KeyValuePair<string, string> pair2)
    {
        return pair1.Value.CompareTo(pair2.Value);
    }
);
var myList = aDictionary.ToList();

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

Context

Stack Overflow Q#289, score: 575

Revisions (0)

No revisions yet.