Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
155 views
in Technique[技术] by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share
...