Georges Oates Larsen
Georges Oates Larsen

Reputation: 7102

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.

Upvotes: 18

Views: 13865

Answers (3)

Manish Basantani
Manish Basantani

Reputation: 17499

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.

Upvotes: 0

Anonymiser
Anonymiser

Reputation: 19

// sort dictionary by value

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

Upvotes: -4

Jon
Jon

Reputation: 437366

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
}

Upvotes: 29

Related Questions