我有:
Public lsAuthors As List(Of String)我想将值添加到这个列表中,但是在添加之前,我需要检查确切的值是否已经在其中。我怎么弄明白呢?
发布于 2014-11-04 10:18:00
您可以使用List.Contains
If Not lsAuthors.Contains(newAuthor) Then
    lsAuthors.Add(newAuthor)
End If或使用LINQ Enumerable.Any
Dim authors = From author In lsAuthors Where author = newAuthor
If Not authors.Any() Then
    lsAuthors.Add(newAuthor)
End If您还可以使用一个有效的HashSet(Of String),而不是列表,如果字符串已经在集合中,则该列表不允许复制并在HashSet.Add中返回False。
 Dim isNew As Boolean = lsAuthors.Add(newAuthor)  ' presuming lsAuthors is a HashSet(Of String)发布于 2014-11-04 10:17:39
泛型列表有一个名为包含的方法,如果选择的类型的默认比较器找到匹配搜索条件的元素,该方法将返回true。
对于(字符串的)列表,这是正常的字符串比较,因此您的代码可能是
Dim newAuthor = "Edgar Allan Poe"
if Not lsAuthors.Contains(newAuthor) Then
    lsAuthors.Add(newAuthor)
End If 另外,如果字符串没有相同的情况,则对字符串的默认比较会考虑两个字符串的不同。因此,如果您试图添加一个名为"edgar allan poe“的作者,而您已经添加了一个名为"Edgar Allan Poe”的作者,那么barebone包含的内容没有注意到它们是相同的。
如果你必须处理好这种情况,那么你需要
....
if Not lsAuthors.Contains(newAuthor, StringComparer.CurrentCultureIgnoreCase) Then
    .....发布于 2014-11-04 10:18:57
要检查元素是否存在于列表中,可以使用list.Contains()方法。如果使用按钮单击以填充字符串列表,请参见代码:
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注释:逐行解释作为注释
https://stackoverflow.com/questions/26732563
复制相似问题