0

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

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

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

1 回答 1

0

使用构造函数创建Listof 键List(IEnumerator<T>),然后使用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);
            }
        }
    }
}
于 2020-01-23T04:03:39.110 回答