Click here to Skip to main content
15,884,099 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I want a sorted dictionary in descending order. How can I do this?
Posted
Updated 13-Dec-17 23:39pm
v2

Dictionary<string, string> dict = new Dictionary<string, string>();

dict.Add("Mango", "1");
dict.Add("Cat", "5");
dict.Add("Rat", "4");
dict.Add("Hare", "2");
dict.Add("Apple", "2");

dict = dict.OrderByDescending(u => u.Value).ToDictionary(z => z.Key, y => y.Value);
//OR
dict = dict.OrderByDescending(keySelector:u => u.Value).ToDictionary(keySelector:z => z.Key, elementSelector:y => y.Value);
 
Share this answer
 
Comments
Deepu S Nair 14-Dec-17 5:45am    
You are answering a question which is nearly 5 years old and already solved .It may attract downvoting your answer.Please try to answer new questions
In this post on CP I demonstrate sorting a Generic Dictionary by both Keys, and Values, in both ascending, and descending, orders, and there's good discussion of issues in sorting Dictionaries: [^].
 
Share this answer
 
v2
store it in var type variable and write :-
var.Sort();
 
Share this answer
 
Comments
BillWoodruff 11-Nov-13 8:09am    
A .NET Generic Dictionary does not have a 'Sort method. You can use the Linq 'OrderBy operator: see my post here for a link to an example of using 'OrderBy.
 
Share this answer
 
Comments
Pushkar Prabhu 25-Nov-13 23:38pm    
thanks..:)

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900