Linq group by in sum column from with where子句

时间:2017-12-15 04:17:26

标签: entity-framework linq

public class PowerPlantsBudgetUsage
    {
         public int  PowerPlantID { get; set; }
   public int TotalWork { get; set; }
    public int ElectricalWorkNo { get; set; }
    public int MechanicalWorkNo { get; set; }
    public int CivilWorkNo { get; set; }
    public int AdminWorkNo { get; set; }
    public int VehicleWorkNo { get; set; }
    [DisplayFormat(DataFormatString = "{0:N}")] 
    public decimal ElectricalBudgetOnly { get; set; }
    public decimal Total { get; set; }
    public string PowerPlantName { get; set; }
    }

 public IActionResult Total()
        {
             var query = _context.REHPData.Include(r => r.PowerPlants).Include(r => r.WorkCategories).GroupBy(r => r.PowerPlantID).Select(s => new PowerPlantsBudgetUsage
        {
            PowerPlantID = s.Key,
            PowerPlantName = s.Select(p => p.PowerPlants.PowerPlantName).First(),
            TotalWork = s.Count(),
            ElectricalWorkNo = s.Count(x => x.WorkCategoriesID == 1),
            MechanicalWorkNo = s.Count(x => x.WorkCategoriesID == 2),
            CivilWorkNo = s.Count(x => x.WorkCategoriesID == 3),
            AdminWorkNo = s.Count(x => x.WorkCategoriesID == 4),
            VehicleWorkNo = s.Count(x => x.WorkCategoriesID == 6),
            Total = s.Sum(x => x.ApprovedAmount),
            ElectricalBudgetOnly = s.Sum(x => x.ApprovedAmount).Where(x=>x.WorkCategoriesID==1) /*this column result is s.Sum(x => x.ApprovedAmount).Where(WorkCategoriesID == 1)  */

        }).ToList();
        return View(query);

        }

我的问题是ElectricalBudgetOnly是ApprovedAmount的总和,其中CategoriesID == 1 powrplantname是测试测试测试测试等......

1 个答案:

答案 0 :(得分:0)

你的错误就是交换了它。

//...
ElectricalBudgetOnly = s.Where(x => x.WorkCategoriesID == 1).Sum(x => x.ApprovedAmount)

首先应用where,然后将where

的结果相加