返回按值排序的只读字典
本文关键字:只读 字典 排序 返回 | 更新日期: 2023-09-27 18:37:04
>我有一个包含Dictionary<string, uint>
的方法。该方法返回从Dictionary<string, uint>
创建的ReadOnlyDictionary<string, uint>
。
我希望返回的字典按值而不是键排序。我搜索了互联网,发现了一些按值排序的 LINQ:
var sorted = from entry in _wordDictionary orderby entry.Value descending select entry;
但是,我不知道如何将它与我要返回的ReadOnlyDictionary<string, uint>
结合使用。
这是我的代码:
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;
}
按照当前的代码,这将返回未排序的字典,但是,如果我改为:
ReadOnlyDictionary<string, uint> result = new ReadOnlyDictionary<string, uint>(sorted);
我收到错误:
The best overloaded method match for 'System.Collections.ObjectModel.ReadOnlyDictionary<string,uint>.ReadOnlyDictionary(System.Collections.Generic.IDictionary<string,uint>)' has some invalid arguments
Argument 1: cannot convert from 'System.Linq.IOrderedEnumerable<System.Collections.Generic.KeyValuePair<string,uint>>' to 'System.Collections.Generic.IDictionary<string,uint>'
如何返回按值排序字典?
编辑
如果相关,这就是我目前能够迭代结果的方式:
var result = WordCounter.GetWordCountDictionary(myString);
foreach (var word in result)
{
Console.WriteLine ("{0} - {1}", word.Key, word.Value);
}
构造函数期待一个IDictionary<string,uint>
但你给了它IOrderedEnumerable<KeyValuePair<string,uint>>
var result = new ReadOnlyDictionary<string, uint>(sorted.ToDictionary(x => x.Key,x => x.Value));
由于您要将排序的结果放入字典中,因此根据 MSDN,枚举期间返回项的顺序是不确定的:
出于枚举的目的,字典中的每个项目都被视为 表示值及其的键值对结构 .key。项的返回顺序未定义。
我建议您在列表中返回结果:
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);
}
ToList 方法将导致System.Collections.Generic.List<KeyValuePair<string, uint>>
解决您的问题是更改行,
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));