SqlDataReader - How to convert the current row to a dictionary SqlDataReader - How to convert the current row to a dictionary sql-server sql-server

SqlDataReader - How to convert the current row to a dictionary


You can use LINQ:

return Enumerable.Range(0, reader.FieldCount)                 .ToDictionary(reader.GetName, reader.GetValue);


Easier than this?:

// Need to read the row in, usually in a while ( opReader.Read ) {} loop...opReader.Read();// Convert current row into a dictionaryDictionary<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.


I came across this question on 3/9/2016 and ended up using the answer provided by SLaks. However, I needed to slightly modify it to:

dataRowDictionary = Enumerable.Range(0, reader.FieldCount).ToDictionary(i => reader.GetName(i), i=> reader.GetValue(i).ToString());

I found guidance from this StackOverflow question: convert dataReader to Dictionary