简体   繁体   English

如何随机选择字符串vb.net

[英]How to randomly select strings vb.net

Is there a simple solution to select random strings in vb.net? 是否有一个简单的解决方案来在vb.net中选择随机字符串? I have a list of about twenty paragraphs where three need to go after each other and I want it to be random. 我有一个大约二十段的清单,其中三段需要互相追逐,我希望它是随机的。 Do I have to create a variable? 我必须创建一个变量吗? Or is there a command that can be run on a button click? 还是有一个可以在单击按钮时运行的命令?

If you have a normal list, this should work: If not, write what kind of list you have. 如果您有一个正常的列表,这应该可以:如果没有,请写下您拥有的列表类型。

    Dim rn As New Random
    Dim selct As String = lst(rn.Next(0, lst.Count - 1))

selct is the output. selct是输出。

Replace lst with your list name. 用您的列表名称替换lst

One (fairly easy way) to accomplish this would be to have a collection of the paragraphs you want to use, and then use PeanutButter.RandomValueGen from the Nuget package PeanutButter.RandomGenerators ( it's open-source too ) 一种(相当简单的方法)可以做到这一点,即拥有要使用的段落的集合,然后使用Nuget包PeanutButter.RandomGenerators中的PeanutButter.RandomValueGen也是开源的

RandomValueGen.GetRandomFrom takes a collection of anything and returns a random item from the collection. RandomValueGen.GetRandomFrom接受所有内容的集合,并从该集合中返回一个随机项。 As a bonus, you can specify a params list of values not to pick, so you can ensure that your paragraphs aren't repeated. 另外,您可以指定一个不可选的值的参数列表,这样可以确保您的段落不会重复。

Whilst the library is written in C#, it can obviously be used from any .NET project. 虽然该库是用C#编写的,但是显然可以在任何.NET项目中使用它。 There are a lot of other generator methods on RandomValueGen too, if you're interested. 如果您感兴趣的话,RandomValueGen上还有很多其他生成器方法。

Full disclosure: I'm the author. 完全公开:我是作者。

if you don't want to have a dependency or need to stay on 4.0 for some odd reason or reason X, you can always try this instead 如果您不希望有依赖关系,或者由于某些奇怪的原因或X原因而需要保持在4.0上,则可以随时尝试使用

Private rnd As New Random
Public Function GetRandom(input As IEnumerable(Of String), itemToGet As Integer) As List(Of String)
    If input.Count < itemToGet Then
        Throw New Exception("List is too small")
    End If

    Dim copy = input.ToList

    Dim result As New List(Of String)
    Dim item As Integer

    While itemToGet > 0
        item = rnd.Next(0, copy.Count)
        result.Add(copy(item))
        copy.RemoveAt(item)

        itemToGet -= 1
    End While

    Return result
End Function 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM