Medise Medise - 1 month ago 7
Vb.net Question

Check if a list of strings contains a value

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 already in it. How do I figure that out?

Answer

You can use List.Contains:

If Not lsAuthors.Contains(newAuthor) Then
    lsAuthors.Add(newAuthor)
End If

or with LINQs Enumerable.Any:

Dim authors = From author In lsAuthors Where author = newAuthor
If Not authors.Any() Then
    lsAuthors.Add(newAuthor)
End If

You could also use an efficient HashSet(Of String) instead of the list which doesn't allow duplicates and returns False in HashSet.Add if the string was already in the set.

 Dim isNew As Boolean = lsAuthors.Add(newAuthor)  ' presuming lsAuthors is a HashSet(Of String)
Comments