Search code examples
c#entity-frameworksum

Get the sum of multiple columns


I have three columns, which I am trying to get the sum of each one returned. I can do it for one column:

var data = db.Test.Sum(x => x.Column1);

I can't figure out how to get the sum for three columns though. I tried selecting the values into and summing them, but that didn't work.

var data = db.Test.Select(x=> new { x.Column1, x.Column3, x.Column3}).Sum();

I am after the result of each column separately, not a sum of all the columns.


Solution

  • var sums = db.Tests
        .GroupBy(x => true)
        .Select(x => new 
        { 
            SumColumn1 = x.Sum(y => y.Column1), 
            SumColumn2 = x.Sum(y => y.Column2), 
            SumColumn3 = x.Sum(y => y.Column3) 
        });
    

    The GroupBy(x => true) statement places all items into a single group. The Select statement the allows operations against each group. In this case the only group is a group of all items that allows us to return the Sum of each column.