小编Rat*_*ose的帖子

根据C#中字符串值的长度对字典进行排序

假设我有这样的字典

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)

但是,此结果现在对于大量数据是可行的。

提前谢谢

c# dictionary sql-order-by

2
推荐指数
1
解决办法
1025
查看次数

标签 统计

c# ×1

dictionary ×1

sql-order-by ×1