2017-03-15 66 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]; 

使用隨機數生成器來訪問一個集合的隨機指數。以上是一個例子。

相關問題