Sorting dictionaries on values.

  • Thread starter Thread starter julio
  • Start date Start date
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
 
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)
 
Back
Top