Saturday, 9 September 2017

c# - How do you sort a dictionary by value?




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 it back to the word.



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


Answer



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));

No comments:

Post a Comment

casting - Why wasn't Tobey Maguire in The Amazing Spider-Man? - Movies & TV

In the Spider-Man franchise, Tobey Maguire is an outstanding performer as a Spider-Man and also reprised his role in the sequels Spider-Man...