【问题标题】:Counting items in a multi-dimensional array计算多维数组中的项目
【发布时间】:2011-07-08 23:25:42
【问题描述】:

如果我有以下数组:

    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

【问题讨论】:

  • 删除了 ASP.NET 标签:这里没有关于 ASP.NET 的内容。
  • 这个数组是给asp.net网站的,所以和asp.net有关系。
  • 不,真的,这个问题与 ASP.NET 没有任何关系,整个问题在控制台应用程序中可以很好地工作就证明了这一点。

标签: vb.net arrays .net-3.5 multidimensional-array


【解决方案1】:

听起来您正在尝试计算数组每个维度中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)

【讨论】:

    【解决方案2】:

    从 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) 中,依此类推...

    【讨论】:

      【解决方案3】:

      注意:我使用了 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()
      

      扩展方法将为您返回为给定索引找到的所有非空项目。从中您可以获取计数、过滤器、查询或随心所欲地使用它们。

      【讨论】:

        猜你喜欢
        • 2012-01-07
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-08-31
        • 2019-06-16
        • 1970-01-01
        • 2016-02-13
        相关资源
        最近更新 更多