Search code examples
vb.netcontains

List(Of ClassA) contains a List(of ClassB) and in it a string. Check if the new string already exists


I have a List(of ClassA) which includes a List(of ClassB). This contains a string called “heading”. I read in a new string using a text box. I want to check if the new string already exists.

My previous code works, but I think it can be done in a more elegant way. I find it a little difficult because I have this class construct. I created a new project for you and only copied the necessary – but reproducible – source code.

Form1.vb

Imports Microsoft.VisualBasic.ControlChars
Public NotInheritable Class FormMain
    Private allA As New List(Of ClassA)
    Private the_new_String As String = ""

    Private Sub FormMain_Load(sender As Object, e As EventArgs) Handles MyBase.Load
        allA.Add(New ClassA)
    End Sub

    Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
        For i As Integer = 0 To allA.Count - 1 Step 1
            For j As Integer = 0 To allA(i).allB.Count - 1 Step 1
                If allA(i).allB(j).Heading = the_new_String Then
                    MessageBox.Show($"Diesen Titel gibt es bereits.{NewLine}This title already exists.",
                                    "",
                                    MessageBoxButtons.OK,
                                    MessageBoxIcon.Information)
                    Return
                End If
            Next
        Next
    End Sub

    Private Sub TextBox1_TextChanged(sender As Object, e As EventArgs) Handles TextBox1.TextChanged
        the_new_String = TextBox1.Text
    End Sub
End Class

ClassA.vb

Public Class ClassA
    Public allB As New List(Of ClassB)

    Public Sub New()
        allB.Add(New ClassB())
    End Sub
End Class

ClassB.vb

Public Class ClassB
    Public Heading As String = "Test"
End Class

Solution

  • If allA.Any(Function(a) a.allB.Any(Function(b) b.Heading = the_new_String)) Then
        'The specified text already exists.
    End If