【问题标题】:How can I get the top categories by join in LINQ?如何通过加入 LINQ 获得热门类别?
【发布时间】:2012-05-04 22:20:13
【问题描述】:

我正在从事分类广告项目,我面临的问题是要获得发布大多数广告的顶级类别,每个类别也有子类别。

我进行了查询,但它适用于我想要的子类别广告,如果任何类别没有子类别,则应计入父类别广告。

var result = (from c in db.Category 
              join a in db.Ad on c.CategoryId equals a.CategoryId 
              where c.ParentId != null 
              group c by c.ParentId into g 
              select new { cat = g.Key, a = g.Count() })
                .OrderBy(c => c.cat)
                .OrderByDescending(a => a.a);

我的分类表是这样的

CategoryId ----- ParentId -----名称

我该怎么做?

【问题讨论】:

    标签: linq entity-framework


    【解决方案1】:

    我想这可以通过单独的查询来完成:

    获取未设置任何 parentId 的类别列表:

    var resultsWithoutSubs = from c in db.Category
                 where c.ParentId == null 
                   && !result.Any(r => cat == c.CategoryId)
                 select c;
    

    根据上面的列表,重复原来的查询:

    var counts =  from c in resultsWithoutSubs
              join a in dbAd on c.CategoryId equals a.CategoryId
              group c by c.CategoryId into g
              select new {cat = g. Key, a = g.Count};
    

    然后您应该能够将这些第一个和最后一个列表合并并对结果进行排序。

    【讨论】:

      【解决方案2】:

      试试这个:

      var results = db.Category
          .Join(db.Ad, cat => cat.CategoryId, 
                ad => ad.CategoryId, (cat, ad) => new { cat, ad } )
          .Where (c => !dbCategory
            .Any (d => c.cat.CategoryId == d.ParentId) && c.cat.ParentId == null)
           .GroupBy (c => c.cat.CategoryId) 
           .Select (g => new  
              { cat = g.Key, a = g.Count () } 
      ); 
      

      【讨论】:

      • 我想统计它的广告,但它正在统计父类别的子类别
      • @StackMe,我想我现在明白你在问什么了。我已经编辑了我的答案。
      • 谢谢你这对我有用
      猜你喜欢
      • 2013-10-10
      • 2012-05-16
      • 1970-01-01
      • 1970-01-01
      • 2014-10-17
      • 1970-01-01
      • 1970-01-01
      • 2017-05-21
      • 2023-04-03
      相关资源
      最近更新 更多