Showing posts with label Dinctionary. Show all posts
Showing posts with label Dinctionary. Show all posts

Sunday, 17 June 2018

Sort Dictionary Based on Value in C#

As we already know that Dictionary works based on Key, Value pair. It provides us great flexibility to deal with lists or nested lists. Sorting a dictionary based on key is very easy but how would we sort it based on its value, I have designed a sample for a hint for you guys to help you with it.

Dictionary<string, int> Dict = new Dictionary<string, int>();
Dict.Add("James", 1);
Dict.Add("Lisa", 4);
Dict.Add("Ann", 2);
Dict.Add("Rick", 3);
var sortedDict = from x in Dict orderby x.Value ascending select x;

Output


You can also apply other options on other datatypes like StartsWith, Contains etc...