开发者

Array in VB .Net

开发者 https://www.devze.com 2023-01-06 01:28 出处:网络
I have 开发者_Python百科an array Newstr(20) When I fill it, I need to know how many of its indexes has been filled ? and find out the values.

I have 开发者_Python百科an array Newstr(20) When I fill it, I need to know how many of its indexes has been filled ? and find out the values.


I need to know how many of its indexes has been filled ?

Arrays don't keep that information. They only know how many spots you allocated. You have to track how many you assigned yourself. More than that, if you're working with a collection where you don't know how many items there will be, arrays are really the wrong choice in the first place. You should use a List(Of T) instead.


You could populate the array with a known string, then test for that string to see how many elements in your array are filled.

I would - however - suggest using an array list. You can get the number of elements added to the list from the Count property. This is the MSDN entry for Array Lists.


In order to find which of the elements have been filled, you can use a LINQ construction like this:

    Dim input() = New String() {"abc", "def", "ghi", "", Nothing}
    Dim output = input.Where(Function(i) Not String.IsNullOrEmpty(i)).ToArray

When you run this code, the output array will contain "abc", "def" and "ghi". You can modify the selector of the Where to suit your preference if you're coding for a different type of array.

For instance the selector for Integer? will be:

input.Where(Function(i) (Not i Is Nothing) Or (i <> 0)).ToArray

Of course, you'll have to be coding in .NET 3.5+ in order to get access to LINQ.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号