Search code examples
c#.netlinqlinq-to-sqlsum

Get sum of two columns in one LINQ query


let's say that I have a table called Items (ID int, Done int, Total int)

I can do it by two queries:

int total = m.Items.Sum(p=>p.Total)
int done = m.Items.Sum(p=>p.Done)

But I'd like to do it in one query, something like this:

var x = from p in m.Items select new { Sum(p.Total), Sum(p.Done)};

Surely there is a way to call aggregate functions from LINQ syntax...?


Solution

  • This will do the trick:

    LINQ Query Syntax:

    from p in m.Items
    group p by 1 into g
    select new
    {
        SumTotal = g.Sum(x => x.Total), 
        SumDone = g.Sum(x => x.Done) 
    };
    

    LINQ Method Syntax:

    m.Items
     .GroupBy(r => 1)
     .Select(g => new 
     {
         SumTotal = g.Sum(x => x.Total), 
         SumDone = g.Sum(x => x.Done) 
     });
    

    Notice that this solution (both syntax) returns a list of 1 item, so you might want to add at the end:

     .FirstOrDefault();