Qiangong2
Qiangong2

Reputation: 159

How to randomly select strings vb.net

Is there a simple solution to select random strings in 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?

Upvotes: 0

Views: 287

Answers (3)

Fredou
Fredou

Reputation: 20140

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

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 

Upvotes: 0

daf
daf

Reputation: 1329

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)

RandomValueGen.GetRandomFrom takes a collection of anything and returns a random item from the collection. 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. There are a lot of other generator methods on RandomValueGen too, if you're interested.

Full disclosure: I'm the author.

Upvotes: 2

BanForFun
BanForFun

Reputation: 752

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.

Replace lst with your list name.

Upvotes: 2

Related Questions