如何從給定的字符串列表中選擇任意隨機字符串?例如:從列表中選擇任意一個隨機字符串
List1: banana, apple, pineapple, mango, dragon-fruit
List2: 10.2.0.212, 10.4.0.221, 10.2.0.223
當我打電話像隨機化(列表1)= somevar一些函數,那麼它將只是從特定列表中的任何字符串。結果somevar將是完全隨機的。如何做呢?非常感謝你:)
如何從給定的字符串列表中選擇任意隨機字符串?例如:從列表中選擇任意一個隨機字符串
List1: banana, apple, pineapple, mango, dragon-fruit
List2: 10.2.0.212, 10.4.0.221, 10.2.0.223
當我打電話像隨機化(列表1)= somevar一些函數,那麼它將只是從特定列表中的任何字符串。結果somevar將是完全隨機的。如何做呢?非常感謝你:)
使用Random
Dim rnd = new Random()
Dim randomFruit = List1(rnd.Next(0, List1.Count))
請注意,您必須重複使用隨機來說,如果你想在一個循環中執行該代碼。否則,值將會重複,因爲隨機數是用當前時間戳初始化的。
所以此工程:
Dim rnd = new Random()
For i As Int32 = 1 To 10
Dim randomFruit = List1(rnd.Next(0, List1.Count))
Console.WriteLine(randomFruit)
Next
,因爲總是使用相同的隨機實例。
但是,這是行不通的:
For i As Int32 = 1 To 10
Dim rnd = new Random()
Dim randomFruit = List1(rnd.Next(0, List1.Count))
Console.WriteLine(randomFruit)
Next
非常感謝,你是一位現場救星!這是我的代碼:Dim RND =新的隨機() 昏暗availServers(0〜2)作爲字符串 availServers(0)= 「Deftones的」 availServers(1)= 「工具」 availServers(2)= 「不安」 。謝謝:D – 2013-02-25 15:03:21
創建的字符串VB List的列表。
創建一個隨機數字發生器。 Random class
以list.count作爲上限調用隨機數生成器的NextInt()方法。
返回列表[NextInt(list.count)]。
完成任務:)
生成一個介於1和列表大小之間的隨機數,並將其用作索引?
試試這個:
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
或只是字符串列表:
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
你可以試試這個:
Dim Rand As New Random
For Each Item In LIST 'Replace LIST with your collection name
Dim NewItem As String = LIST(Rand.Next(0, LIST.Items.Count - 1)) ' Replace "LIST.Items.Count" with the property which determines the number of objects in the collection AND if you want, replace STRING with the type you want. Note that "LIST(...) means to select an item with the specific index. Change this if THIS is not applicable.
'' YOUR CODE HERE TO USE THE VARIABLE NewItem ''
Next
希望這個代碼是有用的。
可能的重複[是否有一種簡單的方法來隨機化VB.NET中的列表?(http://stackoverflow.com/questions/554587/is-there-an-easy-way-to-randomize-a -list-in-vb-net) – 2013-02-25 14:53:18
看起來很複雜。但我會嘗試。 – 2013-02-25 15:01:37