Counting elements in a multidimensional array

If I have the following array:

Dim Array(4, 10) As String Array(0, 0) = "100" Array(0, 1) = "200" Array(1, 0) = "300" Array(1, 1) = "400" Array(1, 2) = "500" Array(1, 3) = "600" 

How to get the following counter:

 0 = 2 1 = 4 
+4
source share
3 answers

It looks like you are trying to count the number of non-Nothing values ​​in each dimension of an array. The following function will allow you to do this.

 Public Function CountNonNothing(ByVal data As String(,), ByVal index As Integer) As Integer Dim count = 0 For j = 0 To data.GetLength(1) - 1 If data(index, j) IsNot Nothing Then count += 1 End If Next Return count End Function 

And he can be called like that

 Dim count1 = CountNonNothing(Array, 0) Dim count2 = CountNonNothing(Array, 1) 
+6
source

Note: I used a C # to VB converter, so hopefully the correct VB syntax.

I made a simple extension method that makes this pretty simple:

 Public NotInheritable Class Extensions Private Sub New() End Sub <System.Runtime.CompilerServices.Extension> _ Public Shared Function GetNonNullItems(Of T)(array As T(,), index As Integer) As IEnumerable(Of T) For i As Integer = 0 To array.GetLength(index) - 1 If array(index, i) IsNot Nothing Then yield Return array(index, i) End If Next End Function End Class 

Then, to use it:

 Dim Array As String(,) = New String(4, 10) {} Array(0, 0) = "100" Array(0, 1) = "200" Array(1, 0) = "300" Array(1, 1) = "400" Array(1, 2) = "500" Array(1, 3) = "600" Dim countArray0 As Integer = Array.GetNonNullItems(0).Count() Dim countArray1 As Integer = Array.GetNonNullItems(1).Count() 

The extension method will provide you with all non-zero elements found for this index. From this you can get an invoice, filter, request or use them as you want.

+2
source

Converted from C #, but there might be something like this.

 Dim count As Integer() = New Integer(Array.GetLength(0) - 1) {} For i As Integer = 0 To Array.GetLength(0) - 1 For j As Integer = 0 To Array.GetLength(1) - 1 If Array(i, j) IsNot Nothing Then count(i) += 1 End If Next Next 

Now counter 0's will be in count(0) , counter 1's will be in count(1) , and so on ...

0
source

Source: https://habr.com/ru/post/1342322/


All Articles