2013-02-25 210 views
2

如何从给定的字符串列表中选择任意随机字符串?例如:从列表中选择任意一个随机字符串

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

当我打电话像随机化(列表1)= somevar一些函数,那么它将只是从特定列表中的任何字符串。结果somevar将是完全随机的。如何做呢?非常感谢你:)

+0

可能的重复[是否有一种简单的方法来随机化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

+0

看起来很复杂。但我会尝试。 – 2013-02-25 15:01:37

回答

6

使用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 
+0

非常感谢,你是一位现场救星!这是我的代码:Dim RND =新的随机() 昏暗availServers(0〜2)作为字符串 availServers(0)= “Deftones的” availServers(1)= “工具” availServers(2)= “不安” 。谢谢:D – 2013-02-25 15:03:21

2

创建的字符串VB List的列表。
创建一个随机数字发生器。 Random class
以list.count作为上限调用随机数生成器的NextInt()方法。
返回列表[NextInt(list.count)]。
完成任务:)

1

生成一个介于1和列表大小之间的随机数,并将其用作索引?

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 
1

你可以试试这个:

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 

希望这个代码是有用的。

相关问题