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

C# SqlDataReader-如何将当前行转换为字典,c#,sql-server,linq,sqldatareader,C#,Sql Server,Linq,Sqldatareader,有没有一种简单的方法可以将SqlDataReader当前行的所有列转换为字典 using (SqlDataReader opReader = command.ExecuteReader()) { // Convert the current row to a dictionary } 谢谢比这更简单吗 // Need to read the row in, usually in a while ( opReader.Read ) {} loop... opReader.Read(); //

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

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

比这更简单吗

// 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));
}
//需要读取中的行,通常是在一段时间内(opReader.read){}循环。。。
opReader.Read();
//将当前行转换为字典
Dictionary dict=新字典();
对于(int-lp=0;lp

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

GetValues方法接受并放入1D数组中的所有值。

这有用吗?

它已经是一个
IDataRecord

这应该给你和字典差不多的访问权限(通过键)。由于行的列数通常不会超过几把,因此查找的性能应该不会有太大的不同。唯一重要的区别是“有效负载”的类型,即使在这里,您的字典也必须使用object作为值类型,因此我将优势赋予IDataRecord。

您可以使用LINQ:

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

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

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

我从这个StackOverflow问题中找到了指导:

作为您问题的答案:如果需要缓存结果,那么缓存字典副本似乎更明智。否则,你最终会有很多未解决的问题readers@Toad如果要缓存结果,可以使用DataTable<代码>MyDataTable.Load(dr)@CadeRoux数据表将读取整个结果集,而不是一行否?@CadeRoux保存到字典的速度比数据表快4-5倍。一个测试:我不明白为什么人们不是简单地回答,而是问“你为什么这么做?或者你为什么问这个?”我们不知道有人问这个问题的实际情况是什么。当你希望在释放连接后查询结果可用时,这是有用的。DataReader对象本质上与创建它们的连接相关联。您的响应看起来很有趣,但我需要在VB.NET中使用它,我不知道如何翻译最后一部分-.ToDictionary(reader.GetName,reader.GetValue)。有什么建议吗?Thanks@bzamfir当前位置您需要
AddressOf
。我对跳上linq is everything的潮流很谨慎,但这太棒了。这是迄今为止提出的最聪明的解决方案。这太棒了,正是我想要做的。它还将空字符串转换为空字符串。