Sort dictionary by value - descending THEN alphabetically C #


Say we have a dictionary: Dict('a' => 2, 'b' => 3, 'c' => 2, 'd' => 4, 'e' => 2)

I used:

var items = from pair in Dict orderby pair.Value descending select pair;

Everything is in order, and the output is:

d: 4
b: 3
c: 2
e: 2
a: 2

Now I want to sort the keys with the same value in alphabetical order to get:

d: 4
b: 3
a: 2
c: 2
e: 2

But I have no idea how to do this.
Any ideas?

+4
source share
3 answers

When ordering 2 values, the syntax will look like this:

var items = from pair in Dict 
            orderby pair.Value descending, 
                    pair.Key 
            select pair;
+8
source

If I understand your problem correctly, it will be as simple as:

var items = Dict.OrderByDescending(r=> r.Value)
                .ThenBy(r=> r.Key);

You need to order several fields using Enumerable.ThenBy(or Enumerable.ThenByDescendingdepending on your requirement)

+8
source
var dict = new Dictionary<string, int>
{
   {"a", 2},
   {"b", 3},
   {"c", 2},
   {"d", 4},
   {"e", 2}
};

var sorted = dict.OrderByDescending(x => x.Value).ThenBy(x => x.Key);
+2
source

Source: https://habr.com/ru/post/1543260/


All Articles