Vitor Reis
Vitor Reis

Reputation: 989

How to get a sum of children values on one LINQ

This is the structure I have:

Program - Description, etc...

Action - Program_Id, Description, etc..

Cost - Action_Id, Value1, Value2, Value3

One Action can Have multiple Costs. What I Need is a query that group this values by Program. Like:

"Program name" | Total of Value1 | Total of Value 2 | Total of the program

This is my effort so far:

var ListByPrograma = from a in db.Actions
    join c in db.Costs on a.Id equals c.Action_Id
    group a by a.Program into p
    select new 
    {
        Program = p.Key,
        actionsQuantity = p.Count(),
        totalValue1 = p.Costs.????
        totalValue2 = ?,
        totalByProgram = ?
    };

Upvotes: 0

Views: 205

Answers (1)

Robaticus
Robaticus

Reputation: 23157

Does something like this work?

var ListByPrograma  = from a in db.Actions
 join c in db.Costs on a.ID equals c.Action_Id
 group new {a,c} by a.Program into p
 select new
 {
    Program = p.Key,
    actionsQty = p.Count ( ),
    totalValue1 = p.Sum(y => y.c.Value1),
    totalValue2 = p.Sum (y => y.c.Value2),
    totalValue3 = p.Sum(y=>y.c.Value3)
};

Upvotes: 2

Related Questions