I'm trying to aggregate the total number of points and coins that a user can achieve in a game on a single challenge. The hierarchy of which the player can get coins and points on a challenge is as follows:
- Challenge
- Step
- StepBlock
- Step
A challenge can have several steps, and a step can have several step blocks.
I've written this as a nested foreach, but this causes a lot of queries to the DB, and I wondered if this is solvable with a LINQ query aggregated on the DB which just returns an object with with two values, one for TotalAchievable points and one for total achievable coins.
The code is as follows:
foreach (var challenge in userChallenges)
{
var coins = 0;
var points = 0;
coins += challenge.CoinsWhenCompleted;
points += challenge.PointsWhenCompleted;
var steps = await db.Steps.Where(s => s.ChallengeId == challenge.ChallengeId).ToListAsync().ConfigureAwait(false);
foreach (var step in steps)
{
coins += step.CoinsWhenCompleted;
points += step.PointsWhenCompleted;
var blocks = await db.StepBlocks.Where(b => b.StepId == step.StepId).ToListAsync().ConfigureAwait(false);
foreach (var block in blocks)
{
coins += block.CoinsWhenCompleted;
points += block.PointsWhenCompleted;
}
}
challenge.TotalPossibleCoins = coins;
challenge.TotalPossiblePoints = points;
}
CoinsWhenCompleted
and PointsWhenCompleted
is the max score on that specific challenge, step or stepblock.
I've tried looking around, but couldn't find when there were several values to be aggregated.
Any help is appreciated, thanks!