Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# Select random element from List

Tags:

c#

random

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.

"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)]);
    }
}
like image 538
Rick Velt Avatar asked Oct 11 '13 12:10

Rick Velt


2 Answers

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]);
}
like image 136
Jonas W Avatar answered Nov 03 '22 00:11

Jonas W


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);
}
like image 42
JJ_Coder4Hire Avatar answered Nov 02 '22 22:11

JJ_Coder4Hire