Visual Basic 将字符串与列表(字符串)中可能不存在的元素进行比较

问题描述 投票:0回答:1

我正在创建一个新的空列表(字符串),然后添加字符串并将其与列表内的元素进行比较。我的问题是,我最终遇到这样的情况:当列表中尚未添加任何内容时,我试图将字符串与 list(0) 进行比较,这会引发索引超出范围错误,我了解其原因。除了下面的两个解决方法示例之外,还有更简单的方法来解决这个问题吗?

Dim TempList As new list(of string)()
if (TempList(0) <> string) then stuff
'this throws an index out of range error

Dim TempList As new list(of string)()
if (TempList.Count >= 1) then
  if (TempList(0) <> string) then stuff
end if
'This works, but requires a separate check of the list

Dim TempList As new list(of string)({"","","","","","","","","","","","","","",""})
if (TempList(0) <> string) then stuff
'This is better, but I don't know how many blank elements to add.
list vb.net
1个回答
0
投票

检查列表是否为空也不错,额外的检查实际上是防止出现问题的最佳方法。但如果字符串永远不是

Nothing
,你也可以使用
ElementAtOrDefault
:

If (TempList.ElementAtOrDefault(0) <> yourString) Then ...

记得添加

Imports System.Linq
,因为这是一个 linq 扩展方法。

所以正如前面提到的,我更喜欢这个:

If (TempList.Any() AndAlso TempList(0) <> yourString) Then ...
© www.soinside.com 2019 - 2024. All rights reserved.