假设我有这样的字典
dict1 = {{[4,bcefgh]},{[5,abcefgh]},{[6,efgh]},{[7,bcefgh]},{[10,cefghi]}}
Run Code Online (Sandbox Code Playgroud)
我想在此字典中根据字符串值的长度对对进行排序,而无需使用额外的循环,即结果应为:
dict1 = {{[6,efgh]},{[4,bcefgh]},{[7,bcefgh]},{[10,cefghi]},{[5,abcefgh]}}
Run Code Online (Sandbox Code Playgroud)
我的最初答案是创建一个单独的字典,该字典具有相同的键和每个对应字符串的长度,以及第三个字典,该字典对如下循环:
foreach (KeyValuePair<int,string> pair in dict1)
{
temp_dict.Add(pair.Key, pair.Value.Count());
}
var items = from pair in temp_dict
orderby pair.Value ascending
select pair;
foreach (KeyValuePair<int, int> pair in items)
{
result_dict.Add(pair.Key, dict1[pair.Key]);
}
Run Code Online (Sandbox Code Playgroud)
但是,此结果现在对于大量数据是可行的。
提前谢谢