Sort list of dictionaries by values in C#


Firstly, let us create a dictionary −

var d = new Dictionary<string, int>(5);

Now add the key and value −

// add key and value
d.Add("car", 25);
d.Add("bus", 28);
d.Add("motorbike", 17);

Use orderby to order by values −

var val = from ele in d
orderby ele.Value ascending
select ele;

We have set ascending above to sort the dictionary in ascending order. You can also use descending.

Display the values in ascending order −

foreach (KeyValuePair ele in val) {
   Console.WriteLine("{0} = {1}", ele.Key, ele.Value);
}

Updated on: 20-Jun-2020

870 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements