我试图在我的表格中选择前五个最常见的值及其计数,并将它们返回到词典中。我能够在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
答案 0 :(得分:5)
您没有指定是否使用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
Obs:我没有测试过。
答案 1 :(得分:3)
假设您正在使用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();