简体   繁体   English

Linq分组依据,降序排列和计数

[英]Linq group by, orderbydescending, and count

So I'm trying to do a linq statement to group two db tables and select the top 25 based on how many reviews each category has. 因此,我正在尝试执行linq语句来对两个数据库表进行分组,并根据每个类别的评论数来选择前25个表。 So my sql statement is 所以我的sql语句是

SELECT TOP 25 BusinessCategories.Category, COUNT(*) as count
FROM Reviews 
JOIN BusinessCategories 
ON BusinessCategories.BusinessID=Reviews.BusinessID 
GROUP BY BusinessCategories.Category
ORDER BY count desc

Which works perfectly. 哪个完美。 So now to try to do this in my web api I'm having troubles. 因此,现在尝试在我的网络API中执行此操作时遇到了麻烦。 This is what I have: 这就是我所拥有的:

var top = (from review in Db.Reviews
           from category in Db.BusinessCategories
           where review.BusinessID == category.BusinessID
           group review by category into reviewgroups
           select new TopBusinessCategory
           {
               BusinessCategory = reviewgroups.Key,
               Count = reviewgroups.Count()
           }
           ).OrderByDescending(x => x.Count).Distinct().Take(25);

This gives me some of the same results, but it looks like when I call the api in the browser all the counts are the same...so I'm doing something wrong. 这给了我一些相同的结果,但是看起来当我在浏览器中调用api时,所有计数都是相同的...所以我做错了什么。

Try this may be it works for you 试试这个可能对你有用

var top = (from review in Db.Reviews
           join category in Db.BusinessCategories
           on review.BusinessID equals category.BusinessID
           group review by category into reviewgroups
           select new TopBusinessCategory
           {
               BusinessCategory = reviewgroups.Key,
               Count = reviewgroups.Key.categoryId.Count() //CategoryId should be any   
                                                           //property of Category or you           
                                                           //can use any property of category
           }).OrderByDescending(x => x.Count).Distinct().Take(25);

Solve the problem by using this 使用此解决问题

[HttpGet]
    [Queryable()]
    public IQueryable<TopBusinessCategory> GetTopBusinessCategories()
    {
        var top = (from p in Db.BusinessCategories
                  join c in Db.Reviews on p.BusinessID equals c.BusinessID into j1
                  from j2 in j1.DefaultIfEmpty()
                  group j2 by p.Category into grouped
                  select new TopBusinessCategory
                  {
                      BusinessCategory = grouped.Key,
                      Count = grouped.Count(t => t.BusinessID != null)
                  }).OrderByDescending(x => x.Count).Take(25);

        return top.AsQueryable();
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM