Search code examples
vb.netwinformslinqtextbox

Find the numbers that do not exist in a String


The problem is as follows: I have a set of numbers from 1 to 80.
In Textbox1.Text I have the following numbers:

TextBox1.Text = "1,4,5,6,7,8,12,13,14,15,16,17,18,19,20,21,22,23,25,28,29,31,33,
                 34,35,36,37,39,40,41,45,46,47,48,49,51,53,54,55,57,59,60,61,62,
                 63,64,66,67, 68,69,70,71,72,73,75,76,77,78,79,80"

How can I display, in TextBox2.Text, the numbers that are not in TextBox1, from 1 to 80?

TextBox2.Text = "2,3,9,10,11 and so on..."

Solution

  • Here are two examples not using LINQ.

    This one uses a Dictionary and a List:

    Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
        Dim n As Integer
        Dim present As New Dictionary(Of Integer, Boolean)
        For Each strValue As String In TextBox1.Text.Split(",".ToCharArray, StringSplitOptions.RemoveEmptyEntries)
            If Integer.TryParse(strValue, n) Then
                present.Add(n, True)
            End If
        Next
    
        Dim notPresent As New List(Of Integer)
        For i As Integer = 1 To 80
            If Not present.ContainsKey(i) Then
                notPresent.Add(i)
            End If
        Next
    
        TextBox2.Text = String.Join(",", notPresent.ToArray)
    End Sub
    

    This one simply uses two Lists:

    Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
        Dim n As Integer
        Dim present As New List(Of Integer)
        For Each strValue As String In TextBox1.Text.Split(",".ToCharArray, StringSplitOptions.RemoveEmptyEntries)
            If Integer.TryParse(strValue, n) Then
                present.Add(n)
            End If
        Next
        present.Sort() ' optional; if you need these sorted for something else
    
        Dim notPresent As New List(Of Integer)
        For i As Integer = 1 To 80
            If present.IndexOf(i) = -1 Then
                notPresent.Add(i)
            End If
        Next
    
        TextBox2.Text = String.Join(",", notPresent.ToArray)
    End Sub