Sorting dictionaries on values.

J

julio

How do you sort a dictionary on __values__? Obviously, i'd like to maintain
the functionality of a dictionary, so apart from the values being sorted, i'd
like to be able to say

k = frequency["foo"];

Otherwise, I could use a List<KeyValuePair<string, int>> and Sort() the list
with the delegate

(x,y)=>return x.Value.CompareTo(y.Value);

thanks
 
M

Morten Wennevik [C# MVP]

julio said:
How do you sort a dictionary on __values__? Obviously, i'd like to maintain
the functionality of a dictionary, so apart from the values being sorted, i'd
like to be able to say

k = frequency["foo"];

Otherwise, I could use a List<KeyValuePair<string, int>> and Sort() the list
with the delegate

(x,y)=>return x.Value.CompareTo(y.Value);

thanks

Hi Julio,

I'm afraid you have to go via List to sort an already created Dictionary.
Or you can use a SortedDictionary<T, U> instead. It will automatically sort
on T.

Another option is to order when looping

foreach (var element in myDictionary.OrderBy(x => x.Key))
Console.WriteLine(element.Value)
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top