Select random object from list c#

核能气质少年 提交于 2020-01-15 11:23:01

问题


I am making a black jack game (more complicated than it needs to be) and I believe I have setup a Dealer class, and then a game class which has a list of Dealers from in it. see below.

Dealer Class

namespace BlackJackClassLibrary
{
    public class Dealer
    {
        public string Name { get; set; }
        public int Endurance { get; set; }
    }
}

Game Class

namespace BlackJackClassLibrary
{
    public class Game
    {
        public List<Dealer> Dealers { get; set; }
    }
}

And then finally I have a method in my Program which adds dealers to the delaers list like so.

    public void SetupData()
    {
        game.Dealers.Add(new Dealer { Name = "Bill", Endurance = 5 });
        game.Dealers.Add(new Dealer { Name = "John", Endurance = 3 });
        game.Dealers.Add(new Dealer { Name = "Johnny", Endurance = 2 });
        game.Dealers.Add(new Dealer { Name = "Robert", Endurance = 1 });
    {

How can I now randomly select a dealer from this list of dealers?


回答1:


Already mentioned in the comments, but to provide an example - use a random number generator.

var random = new Random();

Use it to select a dealer.

var dealer = game.Dealers[random.Next(0, 4)];


来源:https://stackoverflow.com/questions/41905103/select-random-object-from-list-c-sharp

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!