如何获得Linq group by的最后一(5)年ID和take()

时间:2018-03-05 05:53:57

标签: asp.net-mvc linq asp.net-core

我想获得5个年度植物结果的持续5个ID的Budgetyear表。我的查询是......

List<WorkCategories> query = new List<WorkCategories>();
            query = _context.REHPData.OrderByDescending(r=>r.BudgetYearID).Take(5).GroupBy(r => r.BudgetYearID).Select(s =>  new WorkCategories
            {
                ID = s.Key,
                Name = s.Select(r => r.BudgetYear.BudgetYearName).First(),
                Electrical = s.Where(r => r.WorkCategoriesID == 1).Count(),
                Mechanical = s.Where(r => r.WorkCategoriesID == 2).Count(),
                Civil = s.Where(r => r.WorkCategoriesID == 3).Count(),
                Admin = s.Where(r => r.WorkCategoriesID == 4).Count(),
                Vehicel = s.Where(r => r.WorkCategoriesID == 5).Count(),

            }).ToList();

但我的结果是错的。请教我老师..... 这不包括OrderByDescending(r =&gt; r.BudgetYearID).Take(5)结果为enter image description here这包括OrderByDescending(r =&gt; r.BudgetYearID).Take(5)错误的结果是{{ 3}}

1 个答案:

答案 0 :(得分:0)

我相信您的订单执行错误。如果您在OrderByDescending(之前).Take(5) ... GroupBy,那么您将获取最新的BudgetYearId并合并它们,因此您只需处理5行。

我想你想要:

List<WorkCategories> query = new List<WorkCategories>();
query = _context.REHPData.GroupBy(r => r.BudgetYearID)    
                .Select(s =>  new WorkCategories
                    {
                        ID = s.Key,
                        Name = s.Select(r => r.BudgetYear.BudgetYearName).First(),
                        Electrical = s.Where(r => r.WorkCategoriesID == 1).Count(),
                        Mechanical = s.Where(r => r.WorkCategoriesID == 2).Count(),
                        Civil = s.Where(r => r.WorkCategoriesID == 3).Count(),
                        Admin = s.Where(r => r.WorkCategoriesID == 4).Count(),
                        Vehicel = s.Where(r => r.WorkCategoriesID == 5).Count(),
                    }).OrderByDescending(s => s.ID)
                      .Take(5).ToList();