19

What if I want to sort a dictionary in C# with the order determined by its key AND its value. Like descending order by its value and within those having the same value, descending by its key. It seems quite possible to sort only by key or only by value, but by both is quite annoying.

3
  • 3
    It is impossible to sort dictionary, because dictionary stores data as a hash table internally and it can't be reordered. You have to convert it to List first
    – Andrey
    Mar 3, 2011 at 12:15
  • What is the purpose of sorting the key exactly? You could use some besides a Dictionary and you could then sort both the key and value except I don't the purpose of that. If you need a Sorted Collection using a Dictionary is a bad choice. Mar 3, 2011 at 12:16
  • 1
    Please accept an aswer if it was helpful. May 20, 2014 at 11:12

2 Answers 2

30
using System.Linq;
...
IOrderedEnumerable<KeyValuePair<TKey, TValue>> sortedCollection = myDictionary
                    .OrderByDescending(x => x.Value)
                    .ThenByDescending(x => x.Key);
5
  • 2
    what is reason of last ToDistionary? dictionary can't be sorted. You destroy effect of ordering.
    – Andrey
    Mar 3, 2011 at 12:33
  • @Andrey I definitely should test my code before posting! You're right once again. ToDictionary doesn't make any sense at all. IOrderedEnumerable<KeyValuePair<TKey, TValue>> should be sufficient anyway. Mar 3, 2011 at 12:39
  • 3
    What @nawfal means is do use var. May 20, 2014 at 8:40
  • @nawfal Thanks for the translation. I deliberately did not use var so that OP (and other, perhaps less experienced developers) can see the return type at first glance. I try to make my answers as helpful as possible, even if the resulting code sometimes isn't as idiomatic as it could be. May 20, 2014 at 11:11
  • Ya I understand. I wasn't criticizing. Just a pointer to your effort :)
    – nawfal
    May 20, 2014 at 11:34
1

If you need a more complex ordering scheme, implement an IComparer> to use in the overloaded version of OrderBy or OrderByDescending.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.