我有:

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) 代替不允许重复的列表,如果字符串已经在集合中,则在 False 中返回 HashSet.Add
 Dim isNew As Boolean = lsAuthors.Add(newAuthor)  ' presuming lsAuthors is a HashSet(Of String)

关于.net - 检查字符串列表是否包含值,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/26732563/

10-13 06:52