-1

I want to set a list of strings (lets say fruit in the example). And when the button is clicked i would like a random fruit from the list I set to be selected.

So far this is what i got, it only returns a single letter from the fruits in the list instead of the full fruit name.

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()); 
    }
}
Dour High Arch
  • 21,081
  • 29
  • 74
  • 89
Cronk
  • 11
  • 1
  • Generate a random number between (inclusive) 0 and the size of the list minus 1, use that random number as the index to the list when you click the show button. See [here](http://stackoverflow.com/questions/2706500/how-do-i-generate-a-random-int-number-in-c) for generating random numbers. – Quantic Mar 15 '17 at 20:42
  • 3
    What is the question and what have you tried so far? – JeffRSon Mar 15 '17 at 20:46
  • @JeffRson I have edited the question, hope that it helps make things clearer – Cronk Mar 18 '17 at 07:05
  • Don't create Random in Button.Click. Then, what's the purpose/difference of chosenfruit and chosenString - why do you do it twice? Finally - chosenString[number] is only a char, that's why. -- What's wrong with the given answers? – JeffRSon Mar 18 '17 at 14:57

1 Answers1

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

Use a random number generator to access a random index of a collection. Above is an example.

Inisheer
  • 19,806
  • 9
  • 48
  • 81