Dot-Net

檢查字元串列表是否包含值

  • October 19, 2016

我有:

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)

引用自:https://stackoverflow.com/questions/26732563