C# 从列表中选择随机元素

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19318430/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-10 14:44:31  来源:igfitidea点击:

C# Select random element from List

c#random

提问by Rick Velt

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?

我正在创建一个小测验控制台应用程序。我列了一个清单,里面有 3 个问题。如何让程序随机选择一个问题并在控制台中打印出来?

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.

当前上下文中不存在名称“字符串”。

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

“由于Quiz.Questions.main()返回void,返回关键字后不能跟对象表达式”。

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

回答by Bill Gregg

You need a System.Console.WriteLine statment.

您需要一个 System.Console.WriteLine 语句。

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

    }
}

回答by Tim Schmelter

"The name 'string' does not exists in current context"

“当前上下文中不存在名称‘字符串’”

I assume you want

我假设你想要

int index = random.Next(questions.Count); // according to the lower-case random see last paragraph

instead of

代替

int index = Random.Next(strings.Count);

Since there is no variable with the name stringsand you want to remove one question anyway.

由于名称中没有变量,strings您无论如何都想删除一个问题。

Also, you cannot return something from a voidmethod. So create one that returns the list:

此外,您不能从void方法中返回某些内容。所以创建一个返回列表的:

private Random random = new Random();
List<string> GetRemoveQuestion(List<string> questions)
{
        int index = random.Next(questions.Count);
        questions.RemoveAt(index);
        return questions;
}

Edit: last but not least, you cannot use Random.Next. That would presume that there is a staticNextmethod in Randomwhich is not the case. Therefore i have shown above how you create and use an instance. Note that you should not create it i the method itself since it is seeded with the curent time. If you'd call this method very fast you'd get the same "random" value often.

编辑:最后但并非最不重要的是,您不能使用Random.Next. 这将假定有一个staticNext在方法Random是不是这样的。因此,我已经在上面展示了如何创建和使用实例。请注意,您不应该在方法本身中创建它,因为它是用当前时间播种的。如果您非常快速地调用此方法,您将经常获得相同的“随机”值。

Have a look at msdn at the remarks sectionfor more details.

在备注部分查看msdn 以获取更多详细信息。

回答by Jonas W

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

回答by Tom Chantler

You have a couple of minor errors.

你有几个小错误。

You need a reference to a Randobject. You are looking at stringsinstead of questions. You are removing an element instead of selecting it.

你需要一个Rand对象的引用。您正在查看strings而不是questions. 您正在删除一个元素而不是选择它。

Try this:

尝试这个:

void Main()
{
    Random rand = new Random();
    var questions = new List<string>{
        "question1",
        "question2",
        "question3"};
    int index = rand.Next(questions.Count);
    return questions[index];
    // If you want to use Linq then
    // return questions.Skip(index).Take(1);
}

回答by Theodoros Chatzigiannakis

Something like this could be what you want:

这样的事情可能是你想要的:

private Random rng;
T PickRandom<T>(List<T> list)
{
    return list[rng.NextInt(list.Count)];
}

You can call it on your list to get a random element from it.

您可以在列表中调用它以从中获取随机元素。

回答by Kami

Try something like this

尝试这样的事情

public static void main()
{
    var questions = new List<string>{
        "question1",
        "question2",
        "question3"};
    Random rnd = new Random();
    int index = rnd.Next(questions.Count)
    string question  = questions[index];
    questions.RemoveAt(index); // Are you sure you neex to remove?

    System.Console.WriteLine(question);
}

There is a typo in where you are using stringinstead of questions. Also, Randomobject needs to be initalised.

您使用的地方有一个错字,string而不是questions。此外,Random对象需要被初始化。

回答by JJ_Coder4Hire

For other searchers benefit: If you want a depleting list so you ensure you use all items in a random fashion then do this:

对于其他搜索者的好处:如果您想要一个耗尽列表以确保以随机方式使用所有项目,请执行以下操作:

//use the current time to seed random so it's different every time we run it
Random rand = new Random(DateTime.Now.ToString().GetHashCode());
var list = new List<string>{ "item1", "item2", "item3"};

//keep extracting from the list until it's depleted
while (list.Count > 0) {
    int index = rand.Next(0, list.Count);
    Console.WriteLine("Rand Item: " + list[index]);
    list.RemoveAt(index);
}