try using SelectMany()
var total = tasks.SelectMany(x => x.TaskTimes)
.Sum(d => d.Employee.StandardCost * d.TaskHours);
Question
Here is how the model links: project can have multiple tasks, tasks can have multiple times books against it. tasktimes have got taskhours and employee on it Employee has a standardcost.
I am currently working out the sum of the costs of all tasks by looping each task and then multiply the 2 columns i need, and then i sum that.
public decimal CalculateCost(IEnumerable<Task> tasks)
{
decimal total = 0.0M;
foreach (var task in tasks)
{
var cost = from d in task.TaskTimes
select new { total = d.Employee.StandardCost * d.TaskHours };
total = cost.Sum(d => d.total);
}
return total;
}
There must be a better way to do this rather than doing that foreach loop but I can't seem to find the syntax. Is there a more efficient approach or is this the way to do it?
Thanks :)
Solution
try using SelectMany()
var total = tasks.SelectMany(x => x.TaskTimes)
.Sum(d => d.Employee.StandardCost * d.TaskHours);