Select any random string from a list

Fariz Luqman picture Fariz Luqman · Feb 25, 2013 · Viewed 17.9k times · Source

How can I select any random string from a given list of strings? Example:

List1: banana, apple, pineapple, mango, dragon-fruit
List2: 10.2.0.212, 10.4.0.221, 10.2.0.223

When I call some function like randomize(List1) = somevar then it will just take any string from that particular list. The result in somevar will be totally random. How can it be done? Thank you very much :)

Answer

Tim Schmelter picture Tim Schmelter · Feb 25, 2013

Use Random

Dim rnd = new Random()
Dim randomFruit = List1(rnd.Next(0, List1.Count))

Note that you have to reuse the random instance if you want to execute this code in a loop. Otherwise the values would be repeating since random is initialized with the current timestamp.

So this works:

Dim rnd = new Random()
For i As Int32 = 1 To 10
    Dim randomFruit = List1(rnd.Next(0, List1.Count))
    Console.WriteLine(randomFruit)
Next

since always the same random instance is used.

But this won't work:

For i As Int32 = 1 To 10
    Dim rnd = new Random()
    Dim randomFruit = List1(rnd.Next(0, List1.Count))
    Console.WriteLine(randomFruit)
Next