检查字符串列表是否包含某个值

14

我有:

Public lsAuthors As List(Of String)

我想将值添加到这个列表中,在添加之前,我需要检查该值是否已经存在于此列表中。我该如何确定?

4个回答

31
你可以使用 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)

11

通用列表(List)有一个名为Contains的方法,如果所选类型的默认比较器找到与搜索条件匹配的元素,则返回true。

对于List(Of String),这是常规的字符串比较,因此您的代码可能是

Dim newAuthor = "Edgar Allan Poe"
if Not lsAuthors.Contains(newAuthor) Then
    lsAuthors.Add(newAuthor)
End If 

值得一提的是,对于字符串的默认比较会认为两个不同大小写的字符串是不同的。所以,如果你尝试添加一个名为"edgar allan poe"的作者,而你已经添加了一个名为"Edgar Allan Poe"的作者,基本的Contains方法将无法注意到它们是相同的。
如果你需要处理这种情况,那么你需要:

....
if Not lsAuthors.Contains(newAuthor, StringComparer.CurrentCultureIgnoreCase) Then
    .....

我之前尝试过,但出现了“对象引用未设置为对象的实例”的错误。 - Medise
@Medise:然后初始化列表。Public lsAuthors As New List(Of String) - Tim Schmelter

2
要检查列表中是否存在元素,您可以使用 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

注意:每行都有注释解释


0
你可以像这样获取符合条件的项目列表:
Dim lsAuthors As List(Of String)

Dim ResultData As String = lsAuthors.FirstOrDefault(Function(name) name.ToUpper().Contains(SearchFor.ToUpper()))
If ResultData <> String.Empty Then
    ' Item found
Else
    ' Item Not found
End If

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接