Dot-Net
檢查字元串列表是否包含值
我有:
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.AddDim isNew As Boolean = lsAuthors.Add(newAuthor) ' presuming lsAuthors is a HashSet(Of String)