问题
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