Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if a list of strings contains a value

Tags:

.net

list

vb.net

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?

like image 717
Medise Avatar asked Nov 04 '14 10:11

Medise


People also ask

How do you check if a string contains something from a list?

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.

How do you check if a list of strings contains a string in Python?

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.

How do you check if a list contains a value in Python?

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.

How do you check if a list contains a value C#?

List<T>. Contains(T) Method is used to check whether an element is in the List<T> or not.


1 Answers

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)
like image 178
Tim Schmelter Avatar answered Sep 20 '22 17:09

Tim Schmelter