Linq - 使用enum where子句获取对象

时间:2018-03-12 10:09:23

标签: c# linq

我正在制作一个团队可以"起草"玩家。而不是球队选择最好的球员,我希望球队选择最佳球员(总体而言),该球员在一个球队拥有最少球员的位置上进行比赛。

玩家类:

public enum Position { PG,SG,SF,PF,C};

    public string Name { get; private set; }
    public Position Position { get; private set; }
    public int Id { get;}
    public int TeamId { get;}
    public int Overall { get; private set; }
    public int InsideScoring { get; private set; }
    public int MidScoring { get; private set; }
    public int ThreeScoring { get; private set; }
    public int Passing { get; private set; }
    public int BallHandling { get; private set; }
    public int PerimeterD { get; private set; }
    public int InsideD { get; private set; }
    public int Rebounding { get; private set; }
    public int Steals { get; private set; }
    public int Blocks { get; private set; }
    public int Strength { get; private set; }

团队课

    public int Id { get; set; }
    public string Hometown { get; set; }
    public string Teamname { get; set; }
    public Color Teamcolor { get; set; }
    public List<Player> teamPlayers { get; set; } = new List<Player>();

在我的选秀课上,我有以下内容&#34;相关&#34;代码。

void getPlayers()
    {
        allPlayers = new List<Player>();
        allPlayers = sql.Select("Select * from player");
        var source = new BindingSource();
        source.DataSource = allPlayers;
        dgAllPlayers.DataSource = source;
        dgAllPlayers.AutoGenerateColumns = true;
    }
 Team nextTeam;
 List<Player> allPlayers;
 void nextUP()
        {
            if (nextTeam.UserControlled == 0)
            {
                Player ChosenPlayer = aiChoose(nextTeam);
                nextTeam.teamPlayers.Add(ChosenPlayer);
                allPlayers.Remove(ChosenPlayer);
                dgAllPlayers.DataSource = null;
                dgAllPlayers.DataSource = allPlayers;
            }
             nextUP();
        }

    private Player aiChoose(Team team)
    {
        //get best player available
        Player ChosenPlayer = allPlayers.MaxBy(x => x.Overall);
        return ChosenPlayer;
    }

所以在aiChoose方法中我的Linq Query应该被替换。我很清楚这也可以通过使用forloops来实现,但我认为使用Linq更好吗?

1 个答案:

答案 0 :(得分:2)

让最好的球员作为随机剩余位置进行比赛:

Random random = new Random();
Position[] allPositions = Enum.GetValues(typeof(Position)) as Position[];

private Player ChooseNextPlayer(Team team)
{
    var positionsToAllocate = allPositions.Except(team.TeamPlayers.Select(p => p.Position));
    var randomNotAllocatedPosition = positionsToAllocate.ElementAt(random.Next(positionsToAllocate.Count()));

    return allPlayers.Where(p => p.Position == randomNotAllocatedPosition).MaxBy(p => p.Overall);
}
相关问题