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.
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.
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.
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.
using System.Linq;
...
IOrderedEnumerable<KeyValuePair<TKey, TValue>> sortedCollection = myDictionary
.OrderByDescending(x => x.Value)
.ThenByDescending(x => x.Key);
If you need a more complex ordering scheme, implement an IComparer> to use in the overloaded version of OrderBy or OrderByDescending.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With