Select any random string from a list
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 String
s.
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
![Fariz Luqman](https://i.stack.imgur.com/ofvP5.png?s=256&g=1)
Fariz Luqman
My Github profile: https://github.com/farizluqman Visit my website: https://farizluqman.com
Updated on June 18, 2022Comments
-
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 over 11 yearsMuch 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 about 6 yearsYeah, that's basically it. Maybe the OP is new to this, and wants some code examples (as posted by others)