Search code examples
vb.netstringbuilder

turn stringbuilder lines to array then shuffle it


as in my previous question Randomize Lines order in textbox with StringBuilder nobody really answer it with good real answer so i randomize the lines with another way

i want to put to array the final result then shuffle it , then turn it to string again.

   Dim sb As New StringBuilder
       For Each line In texbox1.text.Lines
       sb.AppendLine(line & " CODE-DONE-1")
       sb.AppendLine(line & " CODE-DONE-2")
       sb.AppendLine(line & " CODE-DONE-3")

    Next
textbox2.text = sb.ToString 'Want to randomize Lines Order

my attempt

    Dim sb As New StringBuilder
    For Each line In texbox1.text.Lines
        sb.AppendLine(line & " CODE-DONE-1")
        sb.AppendLine(line & " CODE-DONE-2")
        sb.AppendLine(line & " CODE-DONE-3")

    Next
    Dim list = New List(Of String) From {sb.ToString}
    Dim rnd As New Random()
    Dim shuffled = list.OrderBy(Function(x) rnd.Next()).ToList()
    TextBox2.Text = shuffled

getting alot of errors , i hope you get idea what i want to do , i want to Shuffle output Lines in sb.ToString


Solution

  • Recapping the answer by @Calus Jard and JQSOFT.

    1.Declare a variable at form level for the Random class

    2.Declare a List(Of T)

    3.Add your lines to the list.

    4.Shuffle the list with the OrderBy and display in TextBox2

    Private rand As New Random
    Private Sub OPCode()
        Dim lst As New List(Of String)
        For Each line In TextBox1.Lines
            lst.Add(line & " CODE-DONE-1")
            lst.Add(line & " CODE-DONE-2")
            lst.Add(line & " CODE-DONE-3")
        Next
        TextBox2.Lines = lst.OrderBy(Function(x) rand.Next).ToArray
    End Sub
    

    Credit goes to JQSoft and Calus. This is just a recap.