2014-11-04 57 views

回答

11

您可以使用List.Contains

If Not lsAuthors.Contains(newAuthor) Then 
    lsAuthors.Add(newAuthor) 
End If 

或LINQs Enumerable.Any

Dim authors = From author In lsAuthors Where author = newAuthor 
If Not authors.Any() Then 
    lsAuthors.Add(newAuthor) 
End If 

你也可以使用一個有效的HashSet(Of String)而不是列表,它不允許重複,並返回FalseHashSet.Add如果字符串已經在集合。

Dim isNew As Boolean = lsAuthors.Add(newAuthor) ' presuming lsAuthors is a HashSet(Of String) 
5

通用列表有一個稱爲Contains方法如果用於已選定類型默認的比較發現匹配搜索條件的元素,則返回true。

對於List(串),這是正常的字符串比較,這樣你的代碼可能是

Dim newAuthor = "Edgar Allan Poe" 
if Not lsAuthors.Contains(newAuthor) Then 
    lsAuthors.Add(newAuthor) 
End If 

作爲一個側面說明,對字符串的缺省認爲比較兩個字符串不同,如果他們沒有相同的情況。所以,如果你嘗試添加一個名爲「愛倫坡」一個作家,你已經添加了一個名爲「愛倫坡的」準系統包含沒有注意到它們是相同的。
如果你要管理這種情況,那麼你需要

.... 
if Not lsAuthors.Contains(newAuthor, StringComparer.CurrentCultureIgnoreCase) Then 
    ..... 
+0

我試過之前,我得到一個對象引用未設置爲對象的實例。 – Medise 2014-11-04 10:23:08

+0

@Medise:然後初始化列表。 '公共lsAuthors作爲新列表(字符串)' – 2014-11-04 10:23:54

+0

我做了一個血腥的錯誤,工作,謝謝。 – Medise 2014-11-04 10:26:02

2

要檢查列表中是否存在元素,可以使用list.Contains()方法。如果您正在使用點擊一個按鈕來填充字符串列表,然後看到代碼:

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 

注:一行行的解釋給出評論

0

你可以得到的匹配項的列表你的情況是這樣的:

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 
相關問題