如何在linq查询中对具有多个列的单行求和

时间:2015-02-21 20:33:53

标签: c# linq entity-framework linq-to-entities linq-query-syntax

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

我想总结月份所有水电费,就像1月份有4个电费,电话费,水费,煤气费......这些都在表格的单行中如何得到这些所有和groupby monthID的总和

2 个答案:

答案 0 :(得分:1)

这个返回每月所有账单的总和(两个文件 MonthID 总计):

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) });

这一个每月返还每个账单的总和(五个字段: MonthID TotalElectricity TotalPhone TotalWater < / strong>, 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)
        }
    );

答案 1 :(得分:0)

你可以试试这个。 :

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,其余用于保存该特定月份中所有服务的总和。