Search code examples
sortingdictionarybeef

How do I sort dictionary keys by value?


If I have a Dictionary and a lambda I can use to order the values, how do I get a list or array of the keys sorted by the corresponding value in the dictionary?

For instance, what if I want to sort a Dictionary<String,int> in descending order by the value:

using System.Collections.Generic;
using System;

namespace Program
{

    class Program
    {
        public static void Main()
        {
            let dict = scope Dictionary<String,int>();
            dict.Add("This should be second", 10);
            dict.Add("This should be first", 20);
            dict.Add("This should be fourth", 2);
            dict.Add("This should be third", 7);

            function int(int lhs, int rhs) descendingLambda = (lhs, rhs) => rhs <=> lhs;

            List<String> listOfKeys;

            // sort the keys by value into listOfKeys

            for (let s in listOfKeys)
            {
                Console.WriteLine(s);
            }
        }
    }
}

Solution

  • Create the List of keys using the List(IEnumerator<T>) constructor, then use Sort, wrapping the value orderer in another lambda that accesses the dictionary:

    using System.Collections.Generic;
    using System;
    
    namespace Program
    {
    
        class Program
        {
            public static void Main()
            {
                let dict = scope Dictionary<String,int>();
                dict.Add("This should be second", 10);
                dict.Add("This should be first", 20);
                dict.Add("This should be fourth", 2);
                dict.Add("This should be third", 7);
    
                function int(int lhs, int rhs) descendingLambda = (lhs, rhs) => rhs <=> lhs;
    
                let listOfKeys = scope List<String>(dict.Keys);
    
                listOfKeys.Sort(scope (lhs, rhs) => descendingLambda(dict[lhs], dict[rhs])); 
    
                for (let s in listOfKeys)
                {
                    Console.WriteLine(s);
                }
            }
        }
    }