如何在linq查询中将单行与多列相加

How to sum a single row with multiple columns in linq query

 (from item in _dbEntities.Bills
             where item.Year == year
             select item).GroupBy(x => x.MonthID).Sum(x => x.Phone);

我想按月计算所有水电费的总和,例如 1 月,有 4 个账单电费、phone、水费、煤气费..这些在 table 中排成一行如何计算总和这些全部和 groupby monthID

你可以试试这个。 :

var result= _dbEntities.Bills.Where(b => b.Year == year)
                             .GroupBy(b => b.MonthId)
                             .Select(g=> new { MonthId=g.Key,
                                               Phone=g.Sum(b=>b.Phone),
                                               Water = g.Sum(b => b.Water),
                                               Gas = g.Sum(b => b.Gas),
                                               Electricity = g.Sum(b => b.Electricity)                                         
                                             }).ToList();

我将结果保存在具有五个属性的匿名类型中,第一个保存 MonthId,其余保存该特定月份所有服务的总和。

这个return你每个月所有账单的总和(两个字段MonthIDTotal):

var result = items.Where(b => b.Year == year)
    .Select(b => new { b.MonthID, Total = b.Electricity + b.Gas + b.Phone + b.Water })
    .GroupBy(b => b.MonthID)
    .Select(g => new { MonthID = g.Key, Total = g.Sum(i => i.Total) });

还有这个return每个月每个账单的总和(五个字段:MonthIDTotalElectricityTotalPhone, TotalWater, TotalGas):

var result = items.Where(b => b.Year == year)
    .GroupBy(b => b.MonthID)
    .Select(
        g => new {
            MonthID = g.Key,
            TotalElectricity = g.Sum(b => b.Electricity),
            TotalPhone = g.Sum(b => b.Phone),
            TotalWater = g.Sum(b => b.Water),
            TotalGas = g.Sum(b => b.Gas)
        }
    );