Reputation: 1
I have 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.
Upvotes: 0
Views: 309
Reputation: 12613
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.
Upvotes: 0
Reputation: 480
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.
Upvotes: 0
Reputation: 416131
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.
Upvotes: 3