How to sort a list of dictionaries by values of dictionaries in C#?


Set the list of dictionaries with keys and values.

var d = new Dictionary<string, int>();
d.Add("Zack", 0);
d.Add("Akon", 3);
d.Add("Jack", 2);
d.Add("Tom", 1);

Get and sort the keys.

var val = d.Keys.ToList();
val.Sort();

You can try to run the following code to sort a list of dictionaries by values.

Example

 Live Demo

using System;
using System.Collections.Generic;
using System.Linq;
class Demo {
   static void Main() {
      var d = new Dictionary<string, int>();
      d.Add("Zack", 0);
      d.Add("Akon", 3);
      d.Add("Jack", 2);
      d.Add("Tom", 1);
      // Acquire keys and sort them.
      var val = d.Keys.ToList();
      val.Sort();
      // Loop through keys.
      foreach (var key in val) {
         Console.WriteLine("{0}: {1}", key, d[key]);
      }
   }
}

Output

Akon: 3
Jack: 2
Tom: 1
Zack: 0

Updated on: 23-Jun-2020

342 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements