Search code examples
c#linqentity-frameworklinq-to-entitieslinq-query-syntax

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

I want to sum all utility bills month wise like January there are 4 bills electricity, phone, water,gas.. these are in a single row in table how to get sum of these all and groupby monthID


Solution

  • You could try this. :

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

    I save the result in a anonymous type with five properties, the first one to save the MonthId, and the rest to save the sum of all the services in that particular month.