6

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

1
  • 1
    So why do you prefer this method to using a DataTable? Commented Apr 26, 2013 at 16:23

1 Answer 1

9

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.