gpt4 book ai didi

arrays - 如何将字符串添加到数组 VB.NET?

转载 作者:行者123 更新时间:2023-12-04 14:33:20 25 4
gpt4 key购买 nike

我有一个像这样的数组

Dim array() As String = {}

和以下代码
For i = 0 To membertable.Rows.Count - 1
If InStr(membertable.Rows(i)("name"), txtSearch.Text, CompareMethod.Text) - 1 _
<> -1 And txtSearch.Text.Length >= 3 Then

found = True

'add the item that matches the criteria to the array here.

End If
Next i

因此,代码循环访问访问表的行,每次在“名称”列下找到与我想将该项目添加到数组的条件相匹配的值时。数据库项将始终是一个字符串。

最佳答案

数组具有固定长度。使用 List(Of String)反而:

Dim list As New List(Of String)()

...

list.Add(someString);

注意:列表在内部使用数组并自动调整它们的大小(基本上与 Redim Preserve 相同)。不是在每次添加时将列表大小增加一个元素,而是从数组大小 4 开始,每次数组变得太小时将其大小加倍。这减少了所需的复制操作数量,因为增加数组的大小意味着创建一个新数组并将旧数组的内容复制到新数组。

所以,使用 Redim 真的没有意义。你自己,因为列表会自动和高效地为你制作。

顺便 InStr(...) - 1 <> -1是一个奇怪的条件。它的目的是什么? InStr(...) <> 0是等价的。条件不应该是 InStr(...) <> -1 ?或 membertable.Rows(i)("name").Contains(txtSearch.Text) ?

关于arrays - 如何将字符串添加到数组 VB.NET?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25792892/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com