-2

Hi there im new to programming and wanted to know how can i output 10 random strings from a list. i have 10 strings however only one of them displays in random. i understand that i would need to loop it however i have no idea how to loop items in a list and make it display 10 times in random

 listBox1.Items.Clear();
            var list = new List<string> { "one", "two", "three", "four" ,"five","six","seven","eight","nine","ten"};
            var random = new Random();
            int index = random.Next(list.Count);
            listBox1.Items.Add(list[index]);
sudesh
  • 1
  • 1
  • Put your last two lines of code in a loop that repeats 10 times? – David Sep 27 '21 at 16:37
  • You can suffle the list and then display it, there are many algorithms that do that – Cid Sep 27 '21 at 16:39
  • @David there will then be duplicates – Cid Sep 27 '21 at 16:40
  • 1
    _i have no idea how to loop items_ [Iteration statements (C# reference)](https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/statements/iteration-statements) – 001 Sep 27 '21 at 16:41
  • 3
    @Cid: Does the OP want to randomly pull a string from a list 10 times, or show the entire list in randomly sorted order? The question isn't clear about that. – David Sep 27 '21 at 16:41
  • @David that's true, to me it seemed clear that it was a shuffle problem, but after re-reading again, this point needs indeed clarifications – Cid Sep 27 '21 at 16:45
  • Also try `list.OrderBy((item) => rng.NextDouble());` – John Alexiou Sep 27 '21 at 17:02

1 Answers1

0

You can use a for loop to execute a piece of code multiple times. In this case you don't actually have to loop over the List itself since we don't care about the values itself.

listBox1.Items.Clear();
var list = new List<string> { "one", "two", "three", "four","five","six","seven","eight","nine","ten"};
var random = new Random();

for (var i = 0; i < 10; i++) {
    // We need to call random.Next() in the loop to get a different value each time.
    int index = random.Next(list.Count);
    listBox1.Items.Add(list[index]);
}
justpen
  • 178
  • 1
  • 11