8
A
回答
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)
而不是列表,它不允許重複,並返回False
在HashSet.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
.....
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
相關問題
- 1. 檢查一個列表是否包含一個字符串
- 2. 檢查一個列表的值包含在一個字符串中?
- 3. 檢查Python列表項包含另一個字符串
- 4. 包含在字符串列表中的檢查字符串
- 5. 檢查包含子字符串列表的字符串
- 6. 熊貓 - 檢查字符串列包含一對字符串
- 7. 檢查字符串是否包含嵌套列表的值 - python
- 8. 檢查Python列表項包含從另一個列表中某個字符串在另一字符串
- 9. Applescript:檢查一個字符串是否包含空字符串?
- 10. 檢查字符串列表中的字符子集是否包含在另一個字符串列表中
- 11. 檢查一個字符串,如果它包含一個字符串,它是一個列表蟒蛇內
- 12. 檢查字符串包含Unicode字符
- 13. 檢查字符串包含的字符
- 14. 檢查一個字符串是否只包含特殊字符
- 15. 檢查蟒系列包含在另一個列表中的任何字符串
- 16. 檢查一個字符串是否不包含一些文字
- 17. 如何檢查一個字符串是否包含一個子字符串 - mysql
- 18. 有效檢查一個字符串是否包含另一個字符串
- 19. 檢查一個字符串是否包含另一個字符串
- 20. 檢查一個字符串是否包含一個int
- 21. 檢查一個字符串是否包含數字和字母
- 22. groovy:創建一個包含所有字符串的值列表
- 23. 正則表達式來檢查一個字符串只包含一個字
- 24. Java - 搜索字符串列表if包含另一個字符串列表
- 25. 如何檢查一個單詞列表是否包含任何字符串
- 26. 如何檢查一個字符串是否包含任何一些字符串
- 27. 檢查一個字符串是否包含數字
- 28. F#檢查一個字符串是否只包含數字
- 29. 檢查字符串是否包含一個數字範圍
- 30. Smalltalk:如何檢查一個字符串只包含數字?
我試過之前,我得到一個對象引用未設置爲對象的實例。 – Medise 2014-11-04 10:23:08
@Medise:然後初始化列表。 '公共lsAuthors作爲新列表(字符串)' – 2014-11-04 10:23:54
我做了一個血腥的錯誤,工作,謝謝。 – Medise 2014-11-04 10:26:02