使用LINQ选择最常见的值和计数,并将其分配给字典。

4
我正在尝试选择表中前五个最常见的值及其计数,并在字典中返回它们。我能够在SQL中获得这些值:
SELECT top 5 
    SR_Status,
    COUNT(SR_Status) AS 'value_count'
FROM     
    ServiceRequests
GROUP BY 
    SR_Status
ORDER BY 
    'value_count' DESC;

如何将代码转换为LINQ并将其赋值给字典(Dictionary)?
2个回答

6

您没有说明是否使用Linq2Sql或Linq2Objects,因此让我们假设使用Linq。尝试像这样的东西(请查看每行的注释):

var result = (from s in ServiceRequests // define the data source
             group s by s.SR_Status into g  // group all items by status
             orderby g.Count() descending // order by count descending
             select new { g.Key, Total = g.Count() }) // cast the output
             .Take(5) // take just 5 items
             .ToDictionary(x => x.Key, x => x.Total); // cast to dictionary

注意:我没有测试过它。


列表不是字典。 - SubliemeSiem

5
假设您正在使用 Entity Framework 并且有一个名为 ServiceRequests 的 EntitySet,所有属性名称与列名相同:
var result = context.ServiceRequests.GroupBy(sr => sr.SR_Status)
    .Select(g => new { Key = g.Key, Count = g.Count() })
    .OrderByDescending(kv => kv.Count)
    .Take(5)
    .ToList();

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接