I'm writing a web page to keep the score for a card game. Getting the players score so far would be easy, but there is a twist. During any round the players score can be reset to zero at the start of the round. I don't want to change the score for any previous rounds, so I only want to get a sum of the rounds after (and including) the reset. A player could potentially have their score reset multiple times in a game, or not at all.
I can get the correct score by a multiple stage process of finding the last (if any) score reset, and summing all hands after that (or all hands in no resets) - see PlayerGame.GetPlayerScore.
I'm still trying to get my head around the more intricate ways of doing things with LINQ, and I was wondering if there was a way to do this using a single LINQ statement?
Minimal code:
class Program
{
static void Main(string[] args)
{
PlayerGame playerGame = new PlayerGame();
playerGame.PlayerHands = new List<PlayerHand>
{
new PlayerHand { Round = 1, Score = 10 },
new PlayerHand { Round = 2, Score = 20 },
new PlayerHand { Round = 3, Score = 30 },
new PlayerHand { Round = 4, Score = 40, Reset = true },
new PlayerHand { Round = 5, Score = 50 },
new PlayerHand { Round = 6, Score = 60 }
};
Console.WriteLine($"Players score was {playerGame.GetPlayerScore()}");
Console.ReadLine();
}
}
class PlayerHand
{
public int Round { get; set; }
public int Score { get; set; }
public bool Reset { get; set; } = false;
}
class PlayerGame
{
public List<PlayerHand> PlayerHands { get; set; }
public PlayerGame()
{
PlayerHands = new List<PlayerHand> { };
}
public int GetPlayerScore()
{
// Can all this be simplified to a single LINQ statement?
var ResetIndex = PlayerHands.OrderBy(t => t.Round).LastOrDefault(t => t.Reset == true);
if (ResetIndex != null)
{
return PlayerHands.Where(t => t.Round >= ResetIndex.Round).Sum(t => t.Score);
}
else
{
return PlayerHands.Sum(t => t.Score);
}
}
}
https://dotnetfiddle.net/s5rSqJ
As presented, the players score should be 150. I.e. the score gets reset at the start of Round 4, so the total score is the sum of Rounds 4, 5, and 6.