我有:
Public lsAuthors As List(Of String)
我想将值添加到这个列表中,在添加之前,我需要检查该值是否已经存在于此列表中。我该如何确定?
List.Contains
:If Not lsAuthors.Contains(newAuthor) Then
lsAuthors.Add(newAuthor)
End If
或者使用LINQ的Enumerable.Any
:
Dim authors = From author In lsAuthors Where author = newAuthor
If Not authors.Any() Then
lsAuthors.Add(newAuthor)
End If
你还可以使用一个高效的HashSet(Of String)
,它不允许重复项,并在HashSet.Add
中如果字符串已经存在于集合中则返回False
。
Dim isNew As Boolean = lsAuthors.Add(newAuthor) ' presuming lsAuthors is a HashSet(Of String)
通用列表(List)有一个名为Contains的方法,如果所选类型的默认比较器找到与搜索条件匹配的元素,则返回true。
对于List(Of String),这是常规的字符串比较,因此您的代码可能是
Dim newAuthor = "Edgar Allan Poe"
if Not lsAuthors.Contains(newAuthor) Then
lsAuthors.Add(newAuthor)
End If
值得一提的是,对于字符串的默认比较会认为两个不同大小写的字符串是不同的。所以,如果你尝试添加一个名为"edgar allan poe"的作者,而你已经添加了一个名为"Edgar Allan Poe"的作者,基本的Contains方法将无法注意到它们是相同的。
如果你需要处理这种情况,那么你需要:
....
if Not lsAuthors.Contains(newAuthor, StringComparer.CurrentCultureIgnoreCase) Then
.....
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
注意:每行都有注释解释
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
Public lsAuthors As New List(Of String)
- Tim Schmelter