【问题标题】:Why linq isn't grouping/counting as expected为什么 linq 没有按预期分组/计数
【发布时间】:2014-10-22 14:44:40
【问题描述】:

我正在尝试从我的数据库中获取前 3 个最受欢迎的产品。我有一个名为 clicks 的表,其中包含点击的产品,以及其他一些不重要的字段(如 IP、日期等)。

我想查询数据库统计产品名称相同的总行数,并返回总数以及产品名称。

我的 linq 查询没有达到我的预期。我的代码:

 var results == (from r in this._dc.Clicks
                 group r by r
                 into g
                 orderby g.Count() descending
                 select new { Total = g.Count(), Productc= g.Key.Product }).Take(3).ToList();

问题是,这会返回诸如

之类的结果
11, Shoes
5, Shirts
4, Shirts 

我本来希望结果是

11, Shoes
9, Shirts
something else

为什么我的 Linq 不显示总数?

【问题讨论】:

  • 不应该是group r by r.Product吗?
  • 如果你想按引用类分组,它应该实现IEquatable

标签: linq


【解决方案1】:

您的分组并没有真正分组任何内容。您需要提供一个分组依据,而不是实体本身。显然你应该按Product分组。

var query =
    (from click in this._dc.Clicks
    group click by click.Product into g
    let count = g.Count()
    orderby count descending
    select new { Product = g.Key, Total = count }).Take(3);

【讨论】:

    猜你喜欢
    • 2011-08-28
    • 2014-08-04
    • 2021-01-03
    • 2012-03-04
    • 2018-11-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多