如果我有以下数组:
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"
如何获得以下计数:
0 = 2
1 = 4
答案 0 :(得分:6)
听起来您正在尝试计算数组每个维度中non-Nothing
个值的数量。以下功能将允许您执行此操作
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
它可以像这样调用
Dim count1 = CountNonNothing(Array, 0)
Dim count2 = CountNonNothing(Array, 1)
答案 1 :(得分:2)
注意:我使用了C#到VB转换器,所以希望VB语法正确。
我制作了一个简单的扩展方法,使这很简单:
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
然后使用它:
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()
扩展方法将返回为给定索引找到的所有非空项。通过它,您可以获得计数,过滤,查询或使用它们。
答案 2 :(得分:0)
从c#转换,但它可能是这样的。
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
现在0's
的数量将在count(0)
,1's
的数量将在count(1)
,依此类推......