Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sort dictionary by value - descending THEN alphabetical C#

Tags:

c#

linq


Let's say we have 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 fine and output is:

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

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

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

But I don't have idea how to make it.
Any ideas?

like image 887
rafixwpt Avatar asked Nov 29 '22 11:11

rafixwpt


2 Answers

Ordering by 2 values, the syntax would be:

var items = from pair in Dict 
            orderby pair.Value descending, 
                    pair.Key 
            select pair;
like image 81
crthompson Avatar answered Dec 10 '22 05:12

crthompson


If I understood your problem correctly then it is as simple as:

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

You need to order on multiple fields use Enumerable.ThenBy (or Enumerable.ThenByDescending depending on your requirement)

like image 41
Habib Avatar answered Dec 10 '22 06:12

Habib