多行文本框中的唯一数字

时间:2019-02-05 14:19:01

标签: vb.net

如何为多行文本框编写此代码?

AllNumbers1.AddRange(CType(TabControl2.TabPages(2).Controls("txtIntDraw" & x), TextBox).Text.Split(CChar(",")))

此代码要转换,txtIntDraw.Lines (i).

仅此而已:

  Try
            'Throw everything into a list of String initially.
            Dim AllNumbers1 As New List(Of String)
            'Loop through each TextBox, splitting them by commas
            For x = 1 To Val(txtXCount.Text)
                AllNumbers1.AddRange(CType(TabControl2.TabPages(2).Controls("txtIntDraw" & x), TextBox).Text.Split(CChar(",")))
            Next
            'Remove non-integer entries.
            AllNumbers1.RemoveAll(Function(x) Integer.TryParse(x, New Integer) = False)
            'Join the distinct list to an array, then back to comma separated format into wherever you want it output.
            OutputText1.Text = String.Join(",", AllNumbers1.Distinct().ToArray())
            Dim part() As String = OutputText1.Text.Split(",")
            Dim partCount As Integer = part.Length
            TextBox6.Text = partCount
            Array1()
        Catch ex As Exception
        End Try

1 个答案:

答案 0 :(得分:0)

这很简单吗?不用","来连接不同的数字,而要使用Environment.NewLine

OutputText1.Text = String.Join(Environment.NewLine, AllNumbers1.Distinct())

但是您的代码可以简化为方法

Private Sub doStuff(delimitersIn As String(), delimiterOut As String)
    Dim allNumbers As New List(Of Integer)()
    For x = 1 To CInt(txtXCount.Text)
        allNumbers.AddRange(TabControl2.TabPages(2).Controls("txtIntDraw" & x).Text.Split(delimitersIn, StringSplitOptions.RemoveEmptyEntries).Where(Function(s) Integer.TryParse(s, New Integer)).Select(Function(s) CInt(s)))
    Next
    Dim distinctNumbers = allNumbers.Distinct()
    OutputText1.Text = String.Join(delimiterOut, distinctNumbers)
    TextBox6.Text = distinctNumbers.Count().ToString()
End Sub

使用两个定界符调用它

doStuff({Environment.NewLine, ","}, ",")

或者只是换行符

doStuff({Environment.NewLine}, ",")