Select any random string from a list

19,204

Solution 1

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

Solution 2

Create a List of Strings.
Create a random number generator: Random class
Call Random number generator's NextInt() method with List.Count as the upper bound.
Return List[NextInt(List.count)].
Job done :)

Solution 3

Try this:

Public Function randomize(ByVal lst As ICollection) As Object
    Dim rdm As New Random()
    Dim auxLst As New List(Of Object)(lst)
    Return auxLst(rdm.Next(0, lst.Count))
End Function

Or just for string lists:

Public Function randomize(ByVal lst As ICollection(Of String)) As String
    Dim rdm As New Random()
    Dim auxLst As New List(Of String)(lst)
    Return auxLst(rdm.Next(0, lst.Count))
End Function

Solution 4

Generate a random number between 1 and the size of the list, and use that as an index?

Solution 5

You could try this, this is a simple loop to pick every item from a list, but in a random manner:

Dim Rand As New Random
For C = 0 to LIST.Count - 1 'Replace LIST with the collection name
    Dim RandomItem As STRING = LIST(Rand.Next(0, LIST.Count - 1)) 'Change the item type if needed (STRING)

    '' YOUR CODE HERE TO USE THE VARIABLE NewItem ''

Next
Share:
19,204
Fariz Luqman
Author by

Fariz Luqman

My Github profile: https://github.com/farizluqman Visit my website: https://farizluqman.com

Updated on June 18, 2022

Comments

  • Fariz Luqman
    Fariz Luqman about 2 years

    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 :)

  • Fariz Luqman
    Fariz Luqman over 11 years
    Much thanks, you're a live saver! This is my code: Dim rnd = New Random() Dim availServers(0 To 2) As String availServers(0) = "Deftones" availServers(1) = "Tool" availServers(2) = "Disturbed". Thank you :D
  • Sreenikethan I
    Sreenikethan I about 6 years
    Yeah, that's basically it. Maybe the OP is new to this, and wants some code examples (as posted by others)