我想设置一个字符串列表(在示例中可以说是水果)。当点击按钮时,我希望从我设置的列表中选择一个随机水果。
到目前为止,这是我得到的,它只返回列表中水果的单个字母,而不是完整的水果名称。
private void button1_Click(object sender, EventArgs e)
{
List<string> fruitClass = new List<string>
{
"apple",
"orange",
"banana"
};
Random randomyumyum = new Random();
int randomIndex = randomyumyum.Next(0, 3);
string chosenfruit = fruitClass[randomIndex];
Random singlefruit = new Random();
int randomNumber = singlefruit.Next(fruitClass.Count);
string chosenString = fruitClass[randomNumber];
MessageBox.Show(chosenString[randomyumyum.Next(0, 3)].ToString());
}
}
答案 0 :(得分:1)
List<string> randomStrings = new List<string>
{
"asdfa",
"awefawe"
// to 20 strings
};
// Create a new random # class. This can be reused.
Random random = new Random();
// Get a random number between 0 and 19 (List<string> is 0 based indexed)
int randomIndex = random.Next(randomStrings.Count);
// Get the random string from the list using a random index.
string randomSelectedString = randomStrings[randomIndex];
使用随机数生成器访问集合的随机索引。以上是一个例子。