2017-03-15 63 views
-1

我想设置一个字符串列表(让我们在例子中说水果)。当按钮被点击时,我想从我设置的列表中随机选择一个水果。如何随机选择已设置的字符串?

到目前为止,这是我得到的,它只返回列表中水果的单个字母而不是完整的水果名称。

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

生成(包括)0和列表大小减1之间的随机数,当您单击显示按钮时,使用该随机数作为列表的索引。见[这里](http://stackoverflow.com/questions/2706500/how-do-i-generate-a-random-int-number-in-c)用于生成随机数字。 – Quantic

+3

什么是问题,你到目前为止尝试过什么? – JeffRSon

+0

@JeffRson我编辑了这个问题,希望它有助于使事情更加清晰 – Cronk

回答

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]; 

使用随机数生成器来访问一个集合的随机指数。以上是一个例子。

相关问题