How to choose the top 10 from a dictionary in .NET?

I have a dictionary that is sorted as follows:

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

How to choose the top 10 from this sorted dictionary?

+5
source share
5 answers

As you talk about the decline in your query, I assume you need the last 10 instances. 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 the first 10, just delete descendingand 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);
+22
source

Since you ordered the dictionary descending, then the Takefirst 10 results will select TOP10:

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

Take():

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

This would be more efficient if you take 10 first and then convert them to a dictionary. In cases where it is the other way around, he first converts them into a dictionary, and then takes 10 of it. It will be effective if we have a large list to choose from.

+1
source

All Articles