Medise Medise - 7 months ago 26 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?


You can use List.Contains:

If Not lsAuthors.Contains(newAuthor) Then
End If

or with LINQs Enumerable.Any:

Dim authors = From author In lsAuthors Where author = newAuthor
If Not authors.Any() Then
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)