如何获得按计数列排序的组
很难用简单的英语问这个问题,所以我将展示我想做的事情.
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在查询语法中确实支持Take
和Skip
.
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.