C#lambda简化

Ser*_*pov 0 c# lambda

我有一个班级玩家,玩家有一个镜头列表.每个镜头都有自己的yPos(位置)因为玩家的yPos可以改变但是射击会保持他的位置:

class Player
{
    public string Id { set; get; }
    public int yPos { set; get; }
    public List<Shot> shots;

    public Player(string _Id, int _yPos)
    {
        Id = _Id;
        yPos = _yPos;
    }

}
class Shot
{
    public int yPos { set; get; }
    public Shot(int _yPos)
    {
        yPos = _yPos;
    }
}
Run Code Online (Sandbox Code Playgroud)

然后在游戏中的某个时刻有一个id,我需要找到玩家.并添加他的投篮列表与球员位置的新镜头.
这是我最终得到的:

string tempID = "xxx"; // not important where this temp id is coming from
players.Find(p => p.Id == tempID).shots.Add(new Shot(players.Find(p => p.Id == tempID).yPos));
Run Code Online (Sandbox Code Playgroud)

似乎很好,但看起来很奇怪.有没有办法简化这个语句,所以我不必在一个语句中两次查找同一个玩家?

Jon*_*nas 7

我至少会缓存你的玩家结果:

var player = players.Find(p => p.Id == tempId);
player.shots.Add(new Shot(player.yPos));
Run Code Online (Sandbox Code Playgroud)

  • 或者,在您的Player类中添加"AddShot"方法:AddShot(){this.shots.Add(new Shot(this.ypos)); } (2认同)