对列表求和,但仅针对某个点之后的值

c#

我正在写一个网页来记录纸牌游戏的分数。到目前为止让球员得分很容易,但有一个转折点。在任何回合中,玩家得分可以在回合开始时重置为零。我不想更改任何前几轮的得分,所以我只想在(包括)重置后获得轮数的总和。玩家可能会在一场比赛中多次重置他们的分数,或者根本不重置。

我可以通过一个多阶段的过程来获得正确的分数,即找到最后一次(如果有的话)分数重置,然后对所有手牌(或所有手牌没有重置)求和 - 请参阅 PlayerGame.GetPlayerScore。

我仍然试图了解使用 LINQ 做事情的更复杂的方法,我想知道是否有办法使用单个 LINQ 语句来做到这一点?

最小代码:

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

如图所示,玩家分数应该是 150。 即分数在第 4 回合开始时重置,因此总分是第 4、5 和 6 回合的总和。

以上是对列表求和,但仅针对某个点之后的值的全部内容。
THE END
分享
二维码
< <上一篇
下一篇>>