Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sort a Dictionary by key AND value?

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.

like image 927
Freedom Avatar asked Mar 03 '11 12:03

Freedom


People also ask

Can you sort a dictionary by value?

It is not possible to sort a dictionary, only to get a representation of a dictionary that is sorted. Dictionaries are inherently orderless, but other types, such as lists and tuples, are not. So you need an ordered data type to represent sorted values, which will be a list—probably a list of tuples.

Can we sort dictionary with keys in Python?

Python offers the built-in keys functions keys() and values() functions to sort the dictionary. It takes any iterable as an argument and returns the sorted list of keys. We can use the keys to sort the dictionary in the ascending order.

How do I sort a list of dictionaries by value?

To sort a list of dictionaries according to the value of the specific key, specify the key parameter of the sort() method or the sorted() function. By specifying a function to be applied to each element of the list, it is sorted according to the result of that function.


2 Answers

using System.Linq;
...
IOrderedEnumerable<KeyValuePair<TKey, TValue>> sortedCollection = myDictionary
                    .OrderByDescending(x => x.Value)
                    .ThenByDescending(x => x.Key);
like image 95
Dennis Traub Avatar answered Oct 05 '22 23:10

Dennis Traub


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

like image 25
CheeZe5 Avatar answered Oct 05 '22 23:10

CheeZe5