2

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

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

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 -----名称

我怎样才能做到这一点?

4

2 回答 2

0

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

获取未设置任何 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};

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

于 2012-05-05T12:46:01.800 回答
0

尝试这个:

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 () } 
); 
于 2012-05-05T16:50:25.787 回答