从列表中选择任何随机字符串 [英] Select any random string from a list
问题描述
如何从给定的字符串列表中选择任何随机字符串?示例:
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
当我调用诸如 randomize(List1) = somevar 之类的函数时,它只会从该特定列表中获取任何字符串.somevar 中的结果将是完全随机的.怎么做到呢?非常感谢:)
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 :)
推荐答案
使用 随机
Dim rnd = new Random()
Dim randomFruit = List1(rnd.Next(0, List1.Count))
请注意,如果要在循环中执行此代码,则必须重用随机实例.否则这些值会重复,因为 random 是用当前时间戳初始化的.
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.
所以这是有效的:
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.
但这行不通:
For i As Int32 = 1 To 10
Dim rnd = new Random()
Dim randomFruit = List1(rnd.Next(0, List1.Count))
Console.WriteLine(randomFruit)
Next
这篇关于从列表中选择任何随机字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!