How do you sort a dictionary by value? *

Question

I often have a dictionary of keys & values and need to sort it by value. For example, I have a hash of words and their frequencies, and want to order them by frequency.

There's SortedList which is good for a single value (frequency), but I want to map it back to the word.

SortedDictionary orders by key, not value. Some resort to a custom class, but what's the cleanest way?

Answer

List<KeyValuePair<string, string>> myList = aDictionary.ToList();

myList.Sort(
    delegate(KeyValuePair<string, string> firstPair,
    KeyValuePair<string, string> nextPair)
    {
        return firstPair.Value.CompareTo(nextPair.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 vs2008 (or above).

List<KeyValuePair<string, string>> myList = aDictionary.ToList();

myList.Sort((firstPair,nextPair) =>
    {
        return firstPair.Value.CompareTo(nextPair.Value);
    }
);
< br > via < a class="StackLink" href=" http://stackoverflow.com/questions/289/" >How do you sort a dictionary by value?< /a>
Share on Google Plus

About Cinema Guy

This is a short description in the author block about the author. You edit it by entering text in the "Biographical Info" field in the user admin panel.
    Blogger Comment
    Facebook Comment

0 comments:

Post a Comment