如何按值对字典键进行排序?

How do I sort dictionary keys by value?

如果我有一个 Dictionary 和一个 lambda 可以用来对值进行排序,我如何获得按字典中相应值排序的键列表或数组?

例如,如果我想按值降序对 Dictionary<String,int> 进行排序:

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);
            }
        }
    }
}

使用 List(IEnumerator<T>) 构造函数创建键的 List,然后使用 Sort,将值排序器包装在另一个访问字典的 lambda 中:

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);
            }
        }
    }
}