问题
I'm trying to randomize the final Result here the idea is get the textbox lines do some code , then export it to textbox2 , the code is working but i want to randomize the lines order when exporting to textbox2
Dim newr As New StringBuilder
For Each line In texbox1.text.Lines
newr.AppendLine(line & " CODE-DONE-1")
newr.AppendLine(line & " CODE-DONE-2")
newr.AppendLine(line & " CODE-DONE-3")
Next
textbox2.text = newr.ToString 'Want to randomize Lines Order
Example if i put in textbox1
1
2
3
i want the output in textbox2
3 Code-Done-1
1 Code-Done-3
2 Code-Done-2
3 Code-Done-3
1 Code-Done-1
3 Code-Done-2
2 Code-Done-3
回答1:
Create a class level variable of Random type:
Imports System.Linq
'//
Private ReadOnly rand As New Random
'//
Using the StringBuilder
with For..Loop
way:
Dim sb As New StringBuilder
For Each line In TextBox1.Lines.
Where(Function(x) Not String.IsNullOrWhiteSpace(x)).
OrderBy(Function(x) rand.Next)
sb.AppendLine($"{line} Code-Done")
Next
TextBox2.Text = sb.ToString
The OrderBy(Function(x) rand.Next)
part will shuffle the lines of the first text box and display them in the second one..
Alternatively, you can use the extension methods to achieve that in just one line:
TextBox2.Lines = TextBox1.Lines.
Where(Function(x) Not String.IsNullOrWhiteSpace(x)).
OrderBy(Function(x) rand.Next).
Select(Function(x) $"{x} Code-Done").ToArray
So choose the appropriate way for you.
According to your edit, if you want to append the outputs, replace the StringBuilder
with a class level variable of List(Of String)
type and edit the code as follows:
Imports System.Linq
'//
Private ReadOnly rand As New Random
Private ReadOnly output As New List(Of String)
'//
For Each line In TextBox1.Lines.
Where(Function(x) Not String.IsNullOrWhiteSpace(x))
output.Add($"{line} Code-Done")
Next
TextBox2.Lines = output.OrderBy(Function(x) rand.Next).ToArray
来源:https://stackoverflow.com/questions/61348065/randomize-lines-order-in-textbox-with-stringbuilder