How to select a random string from a list in C#?

Asked

Viewed 52 times

1

Basically, I intended to choose a Random Question from the 'Question List', and when I write the code, it gives me an error in the bold part (the one inside the **).

    private void EscolhaDaPergunta()
    {
        var random = new Random();
        ListaPerguntas =**{ "Pergunta1","Pergunta2","Pergunta3","Pergunta4"};**
        int index = random.Next(ListaPerguntas.Count);
        Console.WriteLine(ListaPerguntas[index]);
    }

1 answer

2


You cannot create the variable in the crazy like this, you need to use the correct syntax to declare it, tell what kind of object you are creating with the type of data you will have inside it.

using System;
using static System.Console;
using System.Collections.Generic;

public class Program {
    public static void Main() {
        var random = new Random();
        var ListaPerguntas = new List<string> { "Pergunta1", "Pergunta2", "Pergunta3", "Pergunta4" };
        WriteLine(ListaPerguntas[random.Next(ListaPerguntas.Count)]);
    }
}

Behold working in the ideone. And in the repl it.. Also put on the Github for future reference.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.