Check if a list of strings contains a value

前端 未结 4 1171
后悔当初
后悔当初 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:13

    The generic List has a method called Contains that returns true if the default comparer for the choosen type finds an element matching the searching criteria.

    For a List(Of String) this is the normal string comparison, so your code could be

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

    As a side note, the default comparison for strings considers two strings different if they don't have the same case. So if your try to add an author named "edgar allan poe" and you already have added one with the name "Edgar Allan Poe" the barebone Contains fails to notice that they are the same.
    If you have to manage this situation then you need

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

提交回复
热议问题