Linq 分组依据 select

Linq Group By with select

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 Total { get; set; }
        public List<string> PowerPlantNameList { 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,
                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),
                PowerPlantNameList = s.Select(x => x.PowerPlants.PowerPlantName).ToList()

            }).ToList();
            return View(query);
[enter image description here][1]
        }

我的问题是 PowerPlantNameList 显示总工作计数 示例总工作量为 5 powrplantname 是测试测试测试测试等等...

My View Result is Look like this

如果我理解得很好,您只想在您的专栏中显示第一个 PowerPlantName。所以将 属性 PowerPlantNameList 更改为 :

public string PowerPlantName { get; set; }

并影响它:

[...]
Total = s.Sum(x => x.ApprovedAmount),
PowerPlantName = s.Select(p => p.PowerPlants.PowerPlantName).First()