Reputation: 361
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?
Upvotes: 15
Views: 94568
Reputation:
To check whether an element is present in a list you can use the list.Contains() method. If you are using a button click to populate the list of strings then see the code:
Public lsAuthors As List(Of String) = New List(Of String) ' Declaration of an empty list of strings
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click ' A button click populates the list
If Not lsAuthors.Contains(TextBox2.Text) Then ' Check whether the list contains the item that to be inserted
lsAuthors.Add(TextBox2.Text) ' If not then add the item to the list
Else
MsgBox("The item Already exist in the list") ' Else alert the user that item already exist
End If
End Sub
Note: Line by line explanation is given as comments
Upvotes: 2
Reputation: 1670
You can get a list of matching items of your condition like this:
Dim lsAuthors As List(Of String)
Dim ResultData As String = lsAuthors.FirstOrDefault(Function(name) name.ToUpper().Contains(SearchFor.ToUpper()))
If ResultData <> String.Empty Then
' Item found
Else
' Item Not found
End If
Upvotes: 0
Reputation: 216353
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
.....
Upvotes: 12
Reputation: 460308
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)
Upvotes: 34