Storing results of a DataReader into an array in VB.NET

Brandon Dusseau picture Brandon Dusseau · Aug 16, 2012 · Viewed 19.6k times · Source

How can I store the results of a DataReader into an array, but still be able to reference them by column name? I essentially want to be able to clone the DataReader's content so that I can close the reader and still have access. I don't want to store the items in a DataTable like everyone suggests.

I've seen a lot of answers, but I couldn't really find any for what I wanted

Answer

Brandon Dusseau picture Brandon Dusseau · Aug 16, 2012

The easiest way I've found to do this is by populating the array with dictionaries with Strings as keys and Objects as values, like so:

' Read data from database
Dim result As New ArrayList()
Dr = myCommand.ExecuteReader()

' Add each entry to array list
While Dr.Read()
    ' Insert each column into a dictionary
    Dim dict As New Dictionary(Of String, Object)
    For count As Integer = 0 To (Dr.FieldCount - 1)
        dict.Add(Dr.GetName(count), Dr(count))
    Next

    ' Add the dictionary to the ArrayList
    result.Add(dict)
End While
Dr.Close()

So, now you could loop through result with a for loop like this:

For Each dat As Dictionary(Of String, Object) In result
     Console.Write(dat("ColName"))
Next

Quite similar to how you would do it if it were just the DataReader:

While Dr.Read()
    Console.Write(Dr("ColName"))
End While

This example is using the MySQL/NET driver, but the same method can be used with the other popular database connectors.