Home > Software engineering >  C# How to output 10 random strings from a list [duplicate]
C# How to output 10 random strings from a list [duplicate]

Time:09-28

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

CodePudding user response:

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