C#获取字典中的前n个值 [英] c# get top n values in dictionary

查看:1590
本文介绍了C#获取字典中的前n个值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在维护一个包含thee关键字及其出现次数的字典.但我想从中获得前5个最大值.如何完成.请在这方面为我提供帮助.

i am maintaining a dictionary that contains thee keywords and its no of occurrences. but i want to get top 5 max values from it. how to accomplish. kindly assist me in this regard. thanks.

推荐答案

我假设您的字符串&不. int中出现的次数.

I''m assuming that your keywords in the string & no. of occurrences in the int.

var myDict = new Dictionary<string,>
                            {{"one", 1}, {"four", 4}, {"two", 2}, {"five", 3}, {"seven", 6}, {"six", 4}};

           var sortedDict = (from entry in myDict orderby entry.Value descending select entry)
               .ToDictionary(pair => pair.Key, pair => pair.Value).Take(5);


我假设您有如下字典myDictionary并提供了解决方案:
I assume you have a dictionary myDictionary as below and providing the solution :
Dictionary<string,int> myDictionary = new Dictionary<string,int>();
        myDictionary.Add("X", 7);
        myDictionary.Add("Y", 5);
        myDictionary.Add("Z", 4);
        myDictionary.Add("A", 9);
        myDictionary.Add("B", 2);

        var sortedItems = (from entry in myDictionary 
                           orderby entry.Value 
                           descending select entry).ToDictionary
                           (
                            pair => pair.Key, 
                            pair => pair.Value
                           ).Take(5);



希望这对您有所帮助.



Hope this helps.


我想对字典进行排序,并排在前5名.
但是,我不确定您正在使用哪个对象.如果您使用的是简单的字典,我认为,可以轻松地对它进行排序和查找最大值.

对于大多数概率,您可以使用排序字典 http://msdn.microsoft. com/en-us/library/f7fta44c%28v = VS.100%29.aspx [ http://msdn.microsoft.com/en-us/library/ms132319.aspx [ ^ ]

那应该为您服务.

希望能有所帮助.如果是这样,请将其标记为答案/赞.
谢谢
Milind
I would think of sorting the dictionary and take top 5.
However, I am not sure which object you are using. If you are using simple dictionary, I don''t think, its readily possible to sort and find max.

With most probabality you can use Sorted dictionary http://msdn.microsoft.com/en-us/library/f7fta44c%28v=VS.100%29.aspx[^]

Or a SortedList object
http://msdn.microsoft.com/en-us/library/ms132319.aspx[^]

That should serve the purpose for you.

Hope that helps. If it does, mark it as answer/upvote.
Thanks
Milind


这篇关于C#获取字典中的前n个值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆