我正在尝试在表格中选择前五个最常见的值及其计数,并将它们返回到词典中.我能够在sql中获取值:
SELECT top 5
SR_Status,
COUNT(SR_Status) AS 'value_count'
FROM
ServiceRequests
GROUP BY
SR_Status
ORDER BY
'value_count' DESC;
Run Code Online (Sandbox Code Playgroud)
如何转换为linq并分配给Dictionary
你没有指定你是使用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
Run Code Online (Sandbox Code Playgroud)
Obs:我没有测试过.
假设您使用实体框架并有一个名为 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();
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
874 次 |
| 最近记录: |