12

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.

Georges Oates Larsen
  • 5,924
  • 10
  • 43
  • 63

3 Answers3

23

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
}
Jon
  • 396,160
  • 71
  • 697
  • 768
  • Ahh,thank you! :) That looks exactly like what I need. This LINQ I keep hearing about, what is it? – Georges Oates Larsen Jan 14 '12 at 03:46
  • 2
    @GeorgesOatesLarsen: It's something you are missing out on by not using it. You might want to read [this](http://msdn.microsoft.com/en-us/library/bb308959.aspx) or Google it (there are bound to be better introductions by now). – Jon Jan 14 '12 at 03:48
0

For completion, the suggested code above (dictionary.OrderBy(p => p.Value)) "will not" work for custom types.

OrderBy makes use of IComparable<T> to be able to compare two objects. If the Value in your dictionary is a custom type then it must implement IComparable<T> to be able to sort values in a proper way.

Read on here.

d219
  • 2,275
  • 5
  • 21
  • 29
Manish Basantani
  • 15,105
  • 22
  • 65
  • 96
  • "must implement IComparable" -- not necessarily. OrderBy() comes in two overloads. One of them behaves as you described, but the second one accepts a custom IComparable object so any value type can be ordered. – DXM Jan 14 '12 at 05:48
  • @DXM, the other overload accepts `IComparer`, not `IComparable`, that wouldn't make much sense. Also, I don't think this has anything to do with value types, it works the same for any type. – svick Jan 14 '12 at 13:24
  • @svick - my bad on the typo, you are right, it's IComparer, but that second overload exactly for what the OP is asking for. You can write your own comparer object to compare anything you want and feed that into OrderBy(). And by "value" I didn't mean value vs. reference. I meant value vs. key. I realize the comparer will work with value types as well as reference types. If agree with this answer that OrderBy can only be used by types that implement IComparable, can you explain what that second overload is for? – DXM Jan 15 '12 at 04:11
  • @DXM, I mostly agree with you, the first overload can only be used by types that implement `IComparable`. But the second overload is not just for the rest of types. It's useful for specifying alternate ordering too (e.g. ordering strings according to different culture). – svick Jan 15 '12 at 12:17
-3

// sort dictionary by value

foreach (KeyValuePair<datatype, datatype> item in dictionary)
{
//do something by value....accessing item.value
}
Anonymiser
  • 21
  • 1
  • 3