Wine Too
Wine Too

Reputation: 4655

Reading data to multidimensional array

I have to read data from database to multidimensional array of unknown size.

    Dim myarray As String()

            Using reader = mcmd.ExecuteReader()
                While (reader.Read())

                    myarray = TryCast(reader("mydataarray"), String())

                End While
            End Using

Here I got in myarray array of strings of last readed row only.

How to get that in 'myarray' will be readed data of all rows from sql result?

Upvotes: 1

Views: 1043

Answers (1)

Daniel
Daniel

Reputation: 13122

Here is code to do what I think you mean:

Using reader = mcmd.ExecuteReader()
   Dim myOuterList as New List(of String())
   While (reader.Read())
      Dim myInnerList as New List(of String)
      'For loop retrieves all columns of data as string
      For i = 0 to reader.FieldCount - 1
         myInnerList.Add(reader.GetString(i))
      Next
      myOuterList.Add(myInnerList.ToArray)
   End While  
End Using 
dim myarray = myOuterList.ToArray

Resulting myarray will be of type String()() I.E. a two-dimensional array of strings.

Though this is possible, I would seriously consider using a typed solution as it will be much easier to understand code dealing with a list of a type than a two-dimensional array.

The typed version would be something like this:

Dim myList As List(Of myType) = reader.OfType(Of IDataRecord) _
                              .Select(Function(data) New myType _
                                        With {.mydataarray = data.item("mydataarray")})
                                              'Additionaly properties if needed.

Upvotes: 1

Related Questions