Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SqlDataReader - How to convert the current row to a dictionary

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

like image 422
Martin Avatar asked May 26 '09 21:05

Martin


2 Answers

You can use LINQ:

return Enumerable.Range(0, reader.FieldCount)                  .ToDictionary(reader.GetName, reader.GetValue); 
like image 79
SLaks Avatar answered Sep 17 '22 13:09

SLaks


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.

like image 21
Cade Roux Avatar answered Sep 20 '22 13:09

Cade Roux