C#从列表中选择随机元素 [英] C# Select random element from List

查看:382
本文介绍了C#从列表中选择随机元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在创建一个小测验控制台应用程序. 我列出了3个问题. 如何让程序随机选择一个问题并将其打印到控制台中?

I am creating a little quiz console application. I have made a list with 3 questions in it. How can I let the program randomly select a question and print it out int the console?

我尝试了一些不同的代码,但由于某种原因似乎无法使它正常工作. 这是我尝试的最后一个代码,是我从该站点的另一个用户那里获得的,但出现错误:

I have tried some different codes but can't seem the get it working for some reason. This is the last code I tried, which I got from another user from this site, but I get the errors:

名称字符串"在当前上下文中不存在.

The name 'string' does not exist in the current context.

由于Quiz.Questions.main()返回 void ,因此return关键字后不能包含对象表达式".

"Since Quiz.Questions.main() returns void, a return keyword must not be followed by an object expression".

这是我尝试的最后一段代码:

Here is the last piece of code which I tried:

class Questions
{
    public static void main()
    {
        var questions = new List<string>{
            "question1",
            "question2",
            "question3"};
        int index = Random.Next(strings.Count);
        questions.RemoveAt(index);
        return questions;

    }

}

谢谢大家的回应. 我通过创建数组而不是列表来解决我的问题. 这是我的代码:

Thank you all for your responses. I have fixed my problem by creating an array instead of an List. This is my code now :

class Questions
{
    public static void main()
    {
        string[] questions = new string[3];
        questions[0] = "question1";
        questions[1] = "question2";
        questions[2] = "question3";
        Random rnd = new Random();
        Console.WriteLine(questions[rnd.Next(0,2)]);
    }
}

推荐答案

您确定要删除一个问题并返回其余问题吗? 您不仅应该选择一个吗?像这样的东西:

Are you sure that you want to remove a question and return the rest of the questions? Should you not only select one? Somthing like this :

public static void main()
{
    var random = new Random();
    var questions = new List<string>{
        "question1",
        "question2",
        "question3"};
    int index = random.Next(questions.Count);
    Console.WriteLine(questions[index]);
}

这篇关于C#从列表中选择随机元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆