如何获得按计数列排序的组 [英] How to get a group ordered by the count column

查看:64
本文介绍了如何获得按计数列排序的组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

很难用简单的英语问这个问题,所以我将展示我想做的事情.

It is hard to ask the question in plain english so I'll show what I'm trying to do.

这是我的SQL代码:

select top 100 [Name], COUNT([Name]) as total from ActivityLog  
where [Timestamp] between '2010-10-28' and '2010-10-29 17:00'  
group by [Name]  
order by total desc  

我需要用LinQ来写.到目前为止,我有以下内容:

I need to write that in LinQ. So far I have the following:

var groups = from ActivityLog log in ctx.ActivityLog
 where log.Timestamp > dateFrom
 where log.Timestamp <= dateTo
 group log by log.Name;

但是我没有COUNT(*)列可以从:(

but I don't have the COUNT(*) column to sort from :(

推荐答案

group ... by ... into语法.等效查询应接近于此:

diceguyd30's answer technically is LINQ and is correct. In fact, the query syntax gets translated to those Queryable/Enumerable methods by the compiler. That said what's missing is using the group ... by ... into syntax. The equivalent query should be close to this:

var query = from log in ctx.ActivityLog
            where log.TimeStamp > dateFrom && log.TimeStamp <= dateTo
            group log by log.Name into grouping
            orderby grouping.Count() descending
            select new { Name = grouping.Key, Total = grouping.Count() };

var result = query.Take(100);

请注意,在C#中,Take(100)方法在查询语法上没有等效项,因此您必须使用扩展方法.另一方面,VB.NET在查询语法中确实支持TakeSkip.

Note that in C# the Take(100) method has no equivalent in query syntax so you must use the extension method. VB.NET, on the other hand, does support Take and Skip in query syntax.

这篇关于如何获得按计数列排序的组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆