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?
Use the any() function to check if a string contains an element from a list, e.g. if any(substring in my_str for substring in my_list): . The any() function will return True if the string contains at least one element from the list and False otherwise.
Use any() to check if a list contains a substring. Call any(iterable) with iterable as a for-loop that checks if any element in the list contains the substring. Alternatively, use a list comprehension to construct a new list containing each element that contains the substring.
To check if the list contains an element in Python, use the “in” operator. The “in” operator checks if the list contains a specific item or not. It can also check if the element exists on the list or not using the list.
List<T>. Contains(T) Method is used to check whether an element is in the List<T> or not.
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With