Sorting 如何按值对字典键进行排序?
如果我有一个Sorting 如何按值对字典键进行排序?,sorting,dictionary,beef,Sorting,Dictionary,Beef,如果我有一个字典和一个lambda可以用来对值进行排序,那么如何获得按字典中相应值排序的键的列表或数组 例如,如果我想按值降序排列字典,该怎么办 using System.Collections.Generic; using System; namespace Program { class Program { public static void Main() { let dict = scope Dictionary
字典
和一个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;
List<String> listOfKeys;
// sort the keys by value into listOfKeys
for (let s in listOfKeys)
{
Console.WriteLine(s);
}
}
}
}
使用System.Collections.Generic;
使用制度;
名称空间程序
{
班级计划
{
公共静态void Main()
{
设dict=scope Dictionary();
dict.Add(“这应该是第二次”,10);
dict.Add(“这应该是第一次”,20);
dict.Add(“这应该是第四个”,2);
dict.Add(“这应该是第三个”,7);
函数int(int-lhs,int-rhs)下降λ=(lhs,rhs)=>rhs-lhs;
密钥列表;
//按值将键排序到键列表中
for(让我们输入键列表)
{
控制台。写入线(s);
}
}
}
}
使用列表(IEnumerator)
构造函数创建键的列表
,然后使用排序
,将值排序器包装在另一个访问字典的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);
}
}
}
}
使用System.Collections.Generic;
使用制度;
名称空间程序
{
班级计划
{
公共静态void Main()
{
设dict=scope Dictionary();
dict.Add(“这应该是第二次”,10);
dict.Add(“这应该是第一次”,20);
dict.Add(“这应该是第四个”,2);
dict.Add(“这应该是第三个”,7);
函数int(int-lhs,int-rhs)下降λ=(lhs,rhs)=>rhs-lhs;
让listOfKeys=范围列表(dict.Keys);
排序(作用域(lhs,rhs)=>下降lambda(dict[lhs],dict[rhs]);
for(让我们输入键列表)
{
控制台。写入线(s);
}
}
}
}