Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# Iterate over Dictionary sorted by value

Is there any way to iterate over a Dictionary, in sorted order, sorted by VALUE not key? I did read abut the "SortedDictionary" object, but sadly, that is sorted by key. One solution would be for me to flip all of my keys with my values, and place them into a SortedDictionary (as they are all integers) -- However, I'm not entirely sure how to go with that one either.

like image 618
Georges Oates Larsen Avatar asked Jan 14 '12 03:01

Georges Oates Larsen


1 Answers

Get the pairs of keys/values out, sort them, and iterate. Dead easy using LINQ:

foreach(var pair in dictionary.OrderBy(p => p.Value)) {
    // work with pair.Key and pair.Value
}
like image 155
Jon Avatar answered Oct 21 '22 00:10

Jon