C# Cλ简化

C# Cλ简化,c#,lambda,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 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;
    }
}

看起来很好,但看起来很奇怪。有没有办法简化此语句,这样我就不必在一个语句中查找同一个播放器两次了?

我至少会缓存您的播放器结果:

var player = players.Find(p => p.Id == tempId);
player.shots.Add(new Shot(player.yPos));

冒着可能陈述一些明显内容的风险,这将减少一次查找,并且可能更具可读性:

string tempID = "xxx";
var player = players.Find(p => p.Id == tempID);
player.shots.Add(new Shot(player.yPos));
接吻:

无意义的长LINQ:

(from p in players
         where p.Id == tempID
         select p).Take(1).ToList().ForEach(p => p.shots.Add(new Shot(p.yPos)));
又好又短的扩展:

players.Find(p => p.Id == tempID).Shoot();
...
static class Extensions
{
    public static void Shoot(this Player p)
    {
        p.shots.Add(new Shot(p.yPos));
    }
}
冷羔羊

(from p in players
         where p.Id == tempID
         let x = new Func<bool>(() => { p.shots.Add(new Shot(p.yPos)); return true; })
         select x()).First();

与其深入玩家,提取其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;
    }

    public void AddShotToYPos()
    {
        shots.Add(new Shot(yPos));
    }
}

我不明白兰博达斯的意思。它们似乎牺牲了可读性而降低了效率。你想要一个快捷方式没关系,我一直都在这样做,但是添加Player.SetCurrentShotLoc方法不是很有意义吗?正如Walkereno所指出的,它们不是很容易阅读,您必须非常清楚何时使用它们。在适当的查询情况下使用它们,而不是在迭代中使用。@Walkereno Lambda的,如果使用得当,可以提供可读性、性能和功能。很久以前我不喜欢Lambda的。那是因为我不理解他们我现在不能没有它们……或者,在你的玩家类中添加一个AddShot方法:AddShot{this.shots.Addnew Shotthis.ypos;}我只是建议做同样的事情:AddShot。英雄所见略同-我将接受那些比W/ReP更多的补充:DI不会考虑缓存接吻,但是你的代码是一个改进。@古文特给出了我的备选方案[现在添加] -特别是LINQ解决方案——我认为是吻:P+ 1我更喜欢这个方法,或者如果你不希望播放器类中的行为,一个扩展方法。
(from p in players
         where p.Id == tempID
         let x = new Func<bool>(() => { p.shots.Add(new Shot(p.yPos)); return true; })
         select x()).First();
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;
    }

    public void AddShotToYPos()
    {
        shots.Add(new Shot(yPos));
    }
}
players.Find(p => p.Id == tempID).AddShotToYPos();