开发者

Counting items in a multi-dimensional array

开发者 https://www.devze.com 2023-02-15 08:26 出处:网络
If I have the following array: Dim Array(4, 10) As String Array(0, 0) = \"100\" Array(0, 1) = \"200\" Array(1, 0) = \"300\"

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 do I get the following coun开发者_运维知识库t:

0 = 2
1 = 4


It sounds like you're trying to count the number of non-Nothing values in each dimension of the array. The following function will allow you to do that

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 it can be invoked like so

Dim count1 = CountNonNothing(Array, 0)
Dim count2 = CountNonNothing(Array, 1)


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

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

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 give you back all non null items found for a given index. From that you can get the count, filter, query, or use them however you want.


Converted from c# but it could 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 count of 0's would be in count(0), count of 1's would be in count(1), so on...

0

精彩评论

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