简体   繁体   中英

How to add a string to an array VB.NET?

I have an array like so

Dim array() As String = {}

and the following code

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

So the code loops through the rows of an access table and every time it finds a value under the "name" column that matches the criteria I want to add that item to the array. the database item will always be a string.

Arrays have a fixed length. Use a List(Of String) instead:

Dim list As New List(Of String)()

...

list.Add(someString)

Note: Lists use arrays internally and resize them automatically (basically doing the same as Redim Preserve ). Instead of increasing the list size by one element at each addition, they start with an array size of 4 and double its size each time the array gets too small. This reduces the number of copy operations needed, since increasing the size of an array means to create a new array and to copy the contents of the old one to the new one.

So, there is really no point in using Redim yourself, as lists make it automatically and efficiently for you.


By the way InStr(...) - 1 <> -1 is a strange condition. What is its purpose? InStr(...) <> 0 is equivalent. Shouldn't the condition be InStr(...) <> -1 ? Or membertable.Rows(i)("name").Contains(txtSearch.Text) ?

To answer your question, you need to re-dimension you array each time you want to add another item:

Redim Preserve array(array.length)

Then add your item to the last one:

array(array.length - 1) = ???

The important thing is using the PRESERVE keyword. Without that, your array will be cleared.

The better way would be to not use an array at all but to use a collection or list.

Use a List(Of String) instead of an array. Also you could LINQ the results. It is also better not to name a variable the same name as a Data Type.

Dim myList = (From dr As DataRow In membertable.Rows Where dr("name").ToString = txtSearch.Text).ToList

It depends on how often you add elements to your array. When it happens many times, you should not use any form of arrays including List s. Maybe LinkedList s are what you're searching for. They provide efficient adding (especially anywhere, further deleting is efficient too). Their only disadvantage is "slow" O(n) indexing. Sequential For Each lookup is always O(n) and there is hardly any difference between them and arrays.

And if you just create the elements and then process them, you can use Iterator Function s (also possible as lambda inside your procedure).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM