使用 StringBuilder 随机化文本框中的行顺序

Randomize Lines order in textbox with StringBuilder

我在这里尝试随机化最终结果,想法是让文本框行执行一些代码,然后将其导出到 textbox2,代码可以工作,但我想在导出到 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

例子 如果我输入 textbox1

1
2
3

我想要文本框 2 中的输出

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

创建一个 class 随机类型的关卡变量:

Imports System.Linq
'//

Private ReadOnly rand As New Random
'//

使用 StringBuilderFor..Loop 方式:

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

OrderBy(Function(x) rand.Next) 部分将打乱第一个文本框的行并显示在第二个文本框中..

或者,您可以使用扩展方法在一行中实现:

TextBox2.Lines = TextBox1.Lines.
    Where(Function(x) Not String.IsNullOrWhiteSpace(x)).
    OrderBy(Function(x) rand.Next).
    Select(Function(x) $"{x} Code-Done").ToArray

所以选择适合你的方式。


根据您的编辑,如果您想要追加输出,请将StringBuilder替换为List(Of String)的class级变量按如下方式输入和编辑代码:

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