SqlDataReader - How to convert the current row to a dictionary

有些话、适合烂在心里 提交于 2019-11-28 17:52:12

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 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.

Mifo

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

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.

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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!