C# SqlDataReader - 如何将当前行转换为字典

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/912948/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-06 02:40:34  来源:igfitidea点击:

SqlDataReader - How to convert the current row to a dictionary

c#sql-serverlinqsqldatareader

提问by Martin

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

有没有一种简单的方法可以将 SqlDataReader 当前行的所有列转换为字典?

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

Thanks

谢谢

采纳答案by SLaks

You can use LINQ:

您可以使用 LINQ:

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

回答by Cade Roux

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.

我仍然不确定为什么您需要从一种类型的集合到另一种类型的这种特殊转换。

回答by shahkalpesh

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

GetValues 方法接受并放入一维数组中的所有值。
这有帮助吗?

回答by Joel Coehoorn

It's already an IDataRecord.

它已经是一个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.

这应该为您提供与字典几乎相同的访问权限(通过键)。由于行通常只有少数几列,因此查找的性能应该不会有太大不同。唯一重要的区别是“有效载荷”的类型,即使在那里你的字典也必须使用 object 作为值类型,所以我给了 IDataRecord 优势。

回答by 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:

我在 2016 年 3 月 9 日遇到了这个问题,最终使用了 SLaks 提供的答案。但是,我需要将其稍微修改为:

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

我从这个 StackOverflow 问题中找到了指导:convert dataReader to Dictionary