所以基本上我遇到了我已经给出的任务的问题.我不会厌倦任务本身的细节,所以我只会给你相关的信息.
我有一本字典,我需要按最高的int [value]排序,准确地排在前五位,我需要能够显示底部的五位.
Dictionary<string, int> dict = new Dictionary<string, int>();
Run Code Online (Sandbox Code Playgroud)
字符串(键)包含已为文本文件读取的单词.整数(值)包含文档中提到它们的次数.
我打算用另一种方式做,但我被告知要用字典做,所以请字典只帮助.我很感激,如果你能解释它应该怎么做,这样我就可以学习并完成任务,因为任务的目的是教育自己,但我发现它有点难...
我提前感谢您的帮助,如果需要更多信息,请告诉我,我会发布!
p.s*_*w.g 29
字典没有任何固有的顺序.但是如果你想获得具有最高(或最低)值的前5个条目,你可以使用一点Linq:
using System.Linq;
...
var top5 = dict.OrderByDescending(pair => pair.Value).Take(5);
var bottom5 = dict.OrderBy(pair => pair.Value).Take(5);
Run Code Online (Sandbox Code Playgroud)
这将返回一个IEnumerable<KeyValuePair<string, int>>
.要把它变回字典,Linq再次可以提供帮助.例如:
var top5 = dict.OrderByDescending(pair => pair.Value).Take(5)
.ToDictionary(pair => pair.Key, pair => pair.Value);
Run Code Online (Sandbox Code Playgroud)
现在,top5
是一个Dictionary<string, int>
只包含5个元素dict
的最高值.
归档时间: |
|
查看次数: |
24890 次 |
最近记录: |