8

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?

4

5 回答 5

25

正如您在查询中提到的降序一样,我假设您需要最近 10 次出现。如果是这样

  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);

如果您需要前 10 个,只需删除descending它就可以正常工作。

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);
于 2012-04-21T06:00:30.640 回答
5

Since you ordered your dictionary descending, then Takeing the first 10 results will be selecting the TOP 10:

var sortedDict = (from entry in dd 
                  orderby entry.Value descending  
                  select entry
                  ).Take(10)
                  .ToDictionary(pair => pair.Key, pair => pair.Value);
于 2012-04-21T06:00:23.787 回答
1

只需使用Take(10)

于 2012-04-21T06:01:07.270 回答
1

您需要使用Take()方法:

var sortedDict = (
    from entry in dd 
    orderby entry.Value descending
    select entry)
    .Take(10)
    .ToDictionary(pair => pair.Key, pair => pair.Value);
于 2012-04-21T06:01:58.050 回答
1
var sortedDict = (from entry in dd orderby entry.Value descending select entry)
                 .Take(10).ToDictionary(pair => pair.Key, pair => pair.Value);

如果您先取 10 然后将它们转换为字典,这将更有效。在反之亦然的情况下,它将首先将它们全部转换为字典,然后从中取出 10 个。如果我们有一个大列表可供选择,这将影响效率。

于 2012-04-21T06:06:30.203 回答