I.Waheed
I.Waheed

Reputation: 147

VB.net How to access row in 2 dimensional array?

I want to read all elements of the first row from a 2-D array in VB.NET. Is there a simple way to do it rather than running a loop. I know that in MATLAB there is possibilty to say: A(1,:) and its done. Thank you.

Upvotes: 3

Views: 2467

Answers (2)

jmcilhinney
jmcilhinney

Reputation: 54417

There is nothing built into the array itself to read without a loop but you could use a LINQ query, e.g.

Dim firstRow = Enumerable.Range(0, myArray.GetUpperBound(1) + 1).
                          Select(Function(i) myArray(0, i))

Note that what is a "row" and what is a "column" is not defined for a 2D array so it's really up to you whether you want to use that or this:

Dim firstRow = Enumerable.Range(0, myArray.GetUpperBound(0) + 1).
                          Select(Function(i) myArray(i, 0))

That gives you an enumerable list of the specified elements so the question is, what do you want to do with it? You haven't actually specified. As it is, all you can really do is enumerate it, which means running a For Each loop over it. That kinda defeats the purpose of avoiding a loop in the first place. If you're saying, without actually saying, that you want those elements in a 1D array then you can call ToArray:

Dim firstRow = Enumerable.Range(0, myArray.GetUpperBound(1) + 1).
                          Select(Function(i) myArray(0, i)).
                          ToArray()

EDIT:

Here is an extension method that you could use to do the job:

Imports System.Runtime.CompilerServices

Public Module ArrayExtensions

    <Extension>
    Public Function GetRow(Of T)(source As T(,), rowIndex As Integer) As T()
        Return Enumerable.Range(0, source.GetUpperBound(1) + 1).
                          Select(Function(i) source(rowIndex, i)).
                          ToArray()
    End Function

End Module

It then makes the calling code much cleaner, especially if you need to do it multiple times, e.g.

Dim firstRow = myArray.GetRow(0)

Upvotes: 4

Gadzin
Gadzin

Reputation: 73

If you don't know size of your array u can use nested loop For Each like this:

For each row in array
    For each col in row
    ''something here like Debug.Write(col.ToString)
    Next
Next

If you know your size and you want specific item in the array you simply do that like in any other loop "for" like this:

For index As Integer = 5 To 5
    For index2 As Integer = 3 To 3
        Debug.Write(index2.ToString)
    Next
Next

Upvotes: 0

Related Questions