views:

912

answers:

3

Is there an easy way to convert all the columns of the current row of a SqlDataReader to a dictionary?

using (SqlDataReader opReader = command.ExecuteReader())
{
// Convert the current row to a dictionary
}

Thanks

+3  A: 

Easier than this?:

// Need to read the row in, usually in a while ( opReader.Read ) {} loop...
opReader.Read();

// Convert current row into a dictionary
Dictionary<string, object> dict = new Dictionary<string, object>();
for( int lp = 0 ; lp < opReader.FieldCount ; lp++ ) {
    dict.Add(opReader.GetName(lp), opReader.GetValue(lp));
}

I'm still not sure why you would need this particular transformation from one type of collection to another.

Cade Roux
As an answer to your question: if one needs to cache the results, it seems wiser to cache the dictionary copy. Otherwise you end up with a lot of open readers
Toad
A: 

GetValues method accepts & puts in, all the values in a 1D array.
Does that help?

shahkalpesh
+1  A: 

It's already an IDataRecord.

That should give you just about the same access (by key) as a dictionary. Since rows don't typically have more than a few handfuls of columns, the performance of the lookups shouldn't be that different. The only important difference is the type of the "payload", and even there your dictionary would have to use object for the value type, so I give the edge to IDataRecord.

Joel Coehoorn
@Joel Coehoorn: This is useful when you'd like the result of a query to be available after you've freed up the connection. DataReader objects are intrinsically tied to the connection they were created with.
sholsinger