Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I select the top 10 from a dictionary in .NET?

Tags:

c#

I have a dictionary which is sorted like this:

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

How can I select top 10 from this sorted dictionary?

like image 345
Dedar Avatar asked Apr 21 '12 05:04

Dedar


Video Answer


1 Answers

As you mention descending in your query, I assume that you need Last 10 Occurences. If so

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


  var sortedDict = dd.OrderByDescending(entry=>entry.Value)
                     .Take(10)
                     .ToDictionary(pair=>pair.Key,pair=>pair.Value);

If you need first 10, just remove descending and it will work fine.

var sortedDict = (from entry in dd orderby entry.Value select entry)
                     .Take(10)
                     .ToDictionary(pair => pair.Key, pair => pair.Value) ;


var sortedDict = dd.OrderBy(entry=>entry.Value)
                     .Take(10)
                     .ToDictionary(pair=>pair.Key,pair=>pair.Value);
like image 77
Marshal Avatar answered Oct 12 '22 03:10

Marshal