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.
2 Answers
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)
9 Comments
myArray(0, i), and second index is the column. The second method assumes the first index is the column and the second index is the row: myArray(i, 0). Note the 0 and i have been swapped in the two versions, and that the GetUpperBound() call is using either 1 or 0 to get either the number of columns or rows respectively.Dim firstRow = myJaggedArray(0). If what you actually want is an array containing the first element of each of the inner arrays then you could basically use the same code as the second snippet, replacing myArray(i, 0) with myArray(i)(0). You can chain a ToArray call on the end if you want.myArray.GetUpperBound(0) + 1 to myArray.Length.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