【问题标题】:How to check all values in an array如何检查数组中的所有值
【发布时间】:2018-12-12 20:23:45
【问题描述】:

我创建了一个包含值 0 - 2 的多维数组,我需要一种方法来检查这个数组以检查任何值是 1 还是 2。我这样做是为了当数组中没有 1 或 2,程序结束,但我不确定如何检查每个元素。 我在下面添加了有问题的数组,但是当程序运行时,它会被值填充。

    Dim ownership = New Integer(7, 7) {{0, 0, 0, 0, 0, 0, 0, 0},
                                       {0, 0, 0, 0, 0, 0, 0, 0},
                                       {0, 0, 0, 0, 0, 0, 0, 0},
                                       {0, 0, 0, 0, 0, 0, 0, 0},
                                       {0, 0, 0, 0, 0, 0, 0, 0},
                                       {0, 0, 0, 0, 0, 0, 0, 0},
                                       {0, 0, 0, 0, 0, 0, 0, 0},
                                       {0, 0, 0, 0, 0, 0, 0, 0}}

有没有办法遍历数组来检查每个值的数量?任何帮助将不胜感激!

【问题讨论】:

  • 如何遍历每个数组并检查每个值是 1 还是 2?

标签: arrays vb.net


【解决方案1】:

如果你喜欢LINQ,可以使用Any()方法检查数组是否包含any> 0

Dim result As Boolean = ownership.OfType(Of Integer).Any(Function(v) v > 0)

如果result = True,则有值> 0

如果您想要引用具有值 > 0 的所有元素,您可以使用 Where() 条件过滤您的数组:此 过滤器 将创建满足条件:

Dim FilterResult = ownership.OfType(Of Integer).
                             Select(Function(elm, idx) New With {elm, idx}).
                             Where(Function(arr) arr.elm > 0).ToArray()

此查询将返回一个数组(它可以是一个列表,使用ToList() 而不是ToArray()),其中包含具有值> 0 的所有元素及其在ownership 数组中的索引(位置)。

注意
正如djv 所评论的那样,LINQ 查询会展平数组索引。
当需要从 1D 到 2D 索引的转换时(使用 LINQ 没关系,可以在查询中使用平面索引),您可以使用这种转换(或类似的东西):

Dim Position2D As (Row As Integer, Col As Integer) =
    (result1(0).idx \ (ownership.GetUpperBound(0) + 1),
     result1(0).idx Mod (ownership.GetUpperBound(1) + 1))

Dim ValueAt2DIndex = ownership(Position2D.Row, Position2D.Col)

【讨论】:

  • 我同意 100% Any() 是要走的路。在第二部分中,idx 是 OfType 之后的一维索引,可能需要使用整数除法和 mod 转换回二维索引
  • @djv 我为此添加了一条注释。
【解决方案2】:

所以这应该会有所帮助

    Dim ownership(,) As Integer = {{0, 0, 0, 0, 0, 0, 0, 0},
                                   {0, 0, 0, 0, 0, 0, 0, 0},
                                   {0, 0, 0, 0, 0, 0, 0, 0},
                                   {0, 0, 0, 0, 0, 0, 0, 0},
                                   {0, 0, 0, 0, 0, 0, 0, 0},
                                   {0, 0, 0, 0, 0, 0, 0, 0},
                                   {0, 0, 0, 0, 0, 0, 0, 0},
                                   {0, 0, 0, 0, 0, 0, 0, 0}}

    Dim fndNZ As Boolean = False
    Dim ctZ As Integer = 0
    For x As Integer = ownership.GetLowerBound(0) To ownership.GetUpperBound(0)
        For y As Integer = ownership.GetLowerBound(1) To ownership.GetUpperBound(1)
            If ownership(x, y) <> 0 Then
                fndNZ = True
                Exit For
            Else
                ctZ += 1
            End If
        Next
        If fndNZ Then Exit For
    Next
    If fndNZ Then
        'exit program
    End If

还有很多需要的,但它可能会有所帮助。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-08-29
    • 1970-01-01
    • 1970-01-01
    • 2016-02-10
    • 1970-01-01
    • 1970-01-01
    • 2021-01-05
    相关资源
    最近更新 更多