简体   繁体   中英

How to add an element to next open location in a string array in VB.net

I have an array of length 10 and only has 2 to 3 elements in it at one time. How do I add an element to the next open location in the array. I'm new to VB.net so any code snippets would really help.

There's no real "next open location" because a String() is fixed sized. If you intialize it with a length of 10 you should fill it immediately. Otherwise there is no way to determine which "slot" is free. Note that in general even Nothing could be a valid value for a string.

I would suggest to use a List(Of String) instead which supports adding items.

If you can ensure that Nothing is never a possible value you can use Array.FindIndex :

Dim firstEmptyIndex As Int32 = Array.FindIndex(strArray, Function(s) s Is Nothing)
If firstEmptyIndex >= 0 Then
    strArray(firstEmptyIndex) = "Foo"
End If

or with Array.IndexOf :

Dim firstEmptyIndex As Int32 = Array.IndexOf(strArray, Nothing)

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