代码之家  ›  专栏  ›  技术社区  ›  sebagomez

如何获取按计数列排序的组

  •  4
  • sebagomez  · 技术社区  · 14 年前

    很难用简单的英语问这个问题,所以我会告诉你我想做什么。

    这是我的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写。到目前为止,我有以下几点:

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

    但我没有 COUNT(*) 排序依据列:(

    2 回复  |  直到 14 年前
        1
  •  3
  •   Community CDub    8 年前

    diceguyd30's answer 从技术上讲是Linq,并且是正确的。实际上,编译器会将查询语法转换为那些可查询/可枚举的方法。上面说缺少的是使用 group ... by ... into syntax . 等效查询应与此接近:

    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 在查询语法中。

        2
  •  7
  •   diceguyd30    14 年前

    恐怕我对流利的语法(而不是查询语法)比较熟悉,但这里有一个可能的LINQ答案:

     ctx.ActivityLog
       .Where(x => x.TimeStamp > dateFrom && x.TimeStamp <= dateTo)
      .GroupBy(x => x.Name)
      .Select(x => new { Name = x.Key, Total = x.Count() })
      .OrderByDescending(x => x.Total)
      .Take(100)
    

    编辑:

    好吧,我走出了我的舒适区,提出了一个查询语法版本,只是不要期望太多。我警告过你我以上的能力:

    (from y in (
        from x in (
            from log in ActivityLog
            where log.Timestamp > dateFrom
            where log.Timestamp <= dateTo
            group log by log.Name)
        select new { Name = x.Key, Total = x.Count() })
    orderby y.Total descending
    select new { Name = y.Name, Total = y.Total }).Take(100)