Check if a list of strings contains a value

前端 未结 4 1161
后悔当初
后悔当初 2020-12-10 04:58

I have:

Public lsAuthors As List(Of String)

I want to add values to this list, but before adding I need to check if the exact value is alre

4条回答
  •  伪装坚强ぢ
    2020-12-10 05:14

    To check whether an element is present in a list you can use the list.Contains() method. If you are using a button click to populate the list of strings then see the code:

    Public lsAuthors As List(Of String) = New List(Of String) ' Declaration of an empty list of strings
    
    Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click ' A button click populates the list
        If Not lsAuthors.Contains(TextBox2.Text) Then ' Check whether the list contains the item that to be inserted
            lsAuthors.Add(TextBox2.Text) ' If not then add the item to the list
        Else
            MsgBox("The item Already exist in the list") ' Else alert the user that item already exist
        End If
    End Sub
    

    Note: Line by line explanation is given as comments

提交回复
热议问题