Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/256.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 如何随机选择已设置的字符串?_C# - Fatal编程技术网

C# 如何随机选择已设置的字符串?

C# 如何随机选择已设置的字符串?,c#,C#,我想在示例中设置一个字符串列表,比如水果。当按钮被点击时,我想从我设置的列表中选择一个随机的水果 到目前为止,这是我得到的,它只返回列表中水果的一个字母,而不是完整的水果名称 private void button1_Click(object sender, EventArgs e) { List<string> fruitClass = new List<string> { "apple", "orange", "banana"

我想在示例中设置一个字符串列表,比如水果。当按钮被点击时,我想从我设置的列表中选择一个随机的水果

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

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之间的随机数,单击“显示”按钮时,将该随机数用作列表的索引。有关生成随机数的信息,请参阅。问题是什么?到目前为止您尝试了什么?@Jefferson我已编辑了该问题,希望它有助于澄清问题。不要在按钮中创建随机数。单击。那么,chosenfruit和chosenString的目的/区别是什么?为什么要做两次?最后-chosenString[数字]只是一个字符,这就是为什么。-给出的答案有什么问题?
    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];