C# 返回按值排序的ReadOnlyDictionary
我有一个包含C# 返回按值排序的ReadOnlyDictionary,c#,linq,dictionary,C#,Linq,Dictionary,我有一个包含字典的方法。该方法返回从字典创建的只读字典 我希望返回的字典按值排序,而不是按键排序。我搜索了互联网,找到了一些按价值排序的LINQ: var sorted = from entry in _wordDictionary orderby entry.Value descending select entry; 但是,我不知道如何将它与我返回的ReadOnlyDictionary结合使用 这是我的密码: public static ReadOnlyDictionary<stri
字典的方法。该方法返回从字典创建的只读字典
我希望返回的字典按值排序,而不是按键排序。我搜索了互联网,找到了一些按价值排序的LINQ:
var sorted = from entry in _wordDictionary orderby entry.Value descending select entry;
但是,我不知道如何将它与我返回的ReadOnlyDictionary
结合使用
这是我的密码:
public static ReadOnlyDictionary<string, uint> GetWordCountDictionary(string stringToCount)
{
Dictionary<string, uint> wordDictionary = new Dictionary<string, uint>();
//Rest of the method here that is not relevant
var sorted = from entry in wordDictionary orderby entry.Value descending select entry;
ReadOnlyDictionary<string, uint> result = new ReadOnlyDictionary<string, uint>(wordDictionary);
return result;
}
构造函数需要一个IDictionary
,但您给它的是IOrderedEnumerable
var result=newreadonlydictionary(sorted.ToDictionary(x=>x.Key,x=>x.Value));
解决问题的方法是更改行
ReadOnlyDictionary<string, uint> result = new ReadOnlyDictionary<string, uint>(sorted);
ReadOnlyDictionary结果=新的ReadOnlyDictionary(已排序);
到
ReadOnlyDictionary结果=新的ReadOnlyDictionary(sorted.ToDictionary(t=>t.Key,t=>t.Value));
因为您要将排序结果放入字典,所以在枚举过程中返回项目的顺序是不确定的,具体如下:
出于枚举的目的,字典中的每一项都被视为
表示值及其属性的KeyValuePair结构
钥匙返回项目的顺序未定义
我建议您以列表的形式返回结果:
var sorted = (from entry in wordDictionary
orderby entry.Value descending
select entry).ToList();
foreach (var word in sorted)
{
Console.WriteLine("{0} - {1}", word.Key, word.Value);
}
在调试时,该方法将生成一个System.Collections.Generic.List
,排序的类型是什么?到目前为止,sorted
查询是对单词字典排序的结果。我不相信可以对readonlydictionary进行排序(普通字典在迭代时不保证顺序)。您很可能返回一个只读的键值对列表。旁注:字典不能保证元素的顺序。因此,按值(或键)对字典进行排序并不意味着什么。排序并返回一个列表或数组<代码>命令人(..)。取(5)
var result = WordCounter.GetWordCountDictionary(myString);
foreach (var word in result)
{
Console.WriteLine ("{0} - {1}", word.Key, word.Value);
}
var result = new ReadOnlyDictionary<string, uint>(sorted.ToDictionary(x => x.Key,x => x.Value));
ReadOnlyDictionary<string, uint> result = new ReadOnlyDictionary<string, uint>(sorted);
ReadOnlyDictionary<string, uint> result = new ReadOnlyDictionary<string, uint>(sorted.ToDictionary(t => t.Key,t => t.Value));
var sorted = (from entry in wordDictionary
orderby entry.Value descending
select entry).ToList();
foreach (var word in sorted)
{
Console.WriteLine("{0} - {1}", word.Key, word.Value);
}