首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >检查字符串列表是否包含一个值。

检查字符串列表是否包含一个值。
EN

Stack Overflow用户
提问于 2014-11-04 10:12:28
回答 4查看 77.8K关注 0票数 13

我有:

代码语言:javascript
运行
复制
Public lsAuthors As List(Of String)

我想将值添加到这个列表中,但是在添加之前,我需要检查确切的值是否已经在其中。我怎么弄明白呢?

EN

回答 4

Stack Overflow用户

回答已采纳

发布于 2014-11-04 10:18:00

您可以使用List.Contains

代码语言:javascript
运行
复制
If Not lsAuthors.Contains(newAuthor) Then
    lsAuthors.Add(newAuthor)
End If

或使用LINQ Enumerable.Any

代码语言:javascript
运行
复制
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

代码语言:javascript
运行
复制
 Dim isNew As Boolean = lsAuthors.Add(newAuthor)  ' presuming lsAuthors is a HashSet(Of String)
票数 27
EN

Stack Overflow用户

发布于 2014-11-04 10:17:39

泛型列表有一个名为包含的方法,如果选择的类型的默认比较器找到匹配搜索条件的元素,该方法将返回true。

对于(字符串的)列表,这是正常的字符串比较,因此您的代码可能是

代码语言:javascript
运行
复制
Dim newAuthor = "Edgar Allan Poe"
if Not lsAuthors.Contains(newAuthor) Then
    lsAuthors.Add(newAuthor)
End If 

另外,如果字符串没有相同的情况,则对字符串的默认比较会考虑两个字符串的不同。因此,如果您试图添加一个名为"edgar allan poe“的作者,而您已经添加了一个名为"Edgar Allan Poe”的作者,那么barebone包含的内容没有注意到它们是相同的。

如果你必须处理好这种情况,那么你需要

代码语言:javascript
运行
复制
....
if Not lsAuthors.Contains(newAuthor, StringComparer.CurrentCultureIgnoreCase) Then
    .....
票数 9
EN

Stack Overflow用户

发布于 2014-11-04 10:18:57

要检查元素是否存在于列表中,可以使用list.Contains()方法。如果使用按钮单击以填充字符串列表,请参见代码:

代码语言:javascript
运行
复制
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

注释:逐行解释作为注释

票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/26732563

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档