How to use LINQ to get multiple totals

Let's say I have the following data in a database.

class Data
{
    public int Category { get; set; }
    public int ValueA { get; set; }
    public int ValueB { get; set; }
}

How can I write a LINQ query to get the sum of ValueA and also the sum of ValueB for all rows with Category == 1?

I know I could load all the data and then use Sum on the loaded data but would prefer to total them in the database.

I know I can use group by but I'm not grouping by anything. I just want these two totals from the data.

Answers


If you are using EF, you can try this:

var result= context.Data.Where(d=>d.Category == 1)
                        .GroupBy(d=>d.Category)
                        .Select(g=>new {
                                         SumA=g.Sum(d=>d.ValueA),
                                         SumB=g.Sum(d=>d.ValueB)
                                       }
                               );

You can group by a constant

var result = from d in context.Data
             where d.Category == 1
             group d by 1 into g
             select 
             {                  
                 ASum = g.Sum(d => d.ValueA), 
                 BSum = g.Sum(d => d.ValueB) 
             };

Or as octavioccl pointed out you can also group by Category since it will be a constant value because of the where clause. But using a constant is how you can achieve what you want in the general case.


Need Your Help

Presenting Modal TableView

iphone presentmodalviewcontroller

I've a tableviewController in a class which I need to present modally from another class. In the modaltableview class, I'm creating tableview in viewDidLoad and apart from this there are tableView

preg_match: nothing to repeat / no match

php regex

I am using this: if(!preg_match('/^+[0-9]$/', '+1234567'))