【发布时间】:2026-01-08 22:35:02
【问题描述】:
有没有一种简单的方法可以将 SqlDataReader 的当前行的所有列转换为字典?
using (SqlDataReader opReader = command.ExecuteReader())
{
// Convert the current row to a dictionary
}
谢谢
【问题讨论】:
标签: c# sql-server linq sqldatareader
有没有一种简单的方法可以将 SqlDataReader 的当前行的所有列转换为字典?
using (SqlDataReader opReader = command.ExecuteReader())
{
// Convert the current row to a dictionary
}
谢谢
【问题讨论】:
标签: c# sql-server linq sqldatareader
您可以使用 LINQ:
return Enumerable.Range(0, reader.FieldCount)
.ToDictionary(reader.GetName, reader.GetValue);
【讨论】:
AddressOf。
比这容易吗?:
// 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));
}
我仍然不确定您为什么需要从一种集合类型到另一种集合的这种特殊转换。
【讨论】:
MyDataTable.Load(dr);
我在 2016 年 3 月 9 日遇到了这个问题,最终使用了 SLaks 提供的答案。但是,我需要稍微修改一下:
dataRowDictionary = Enumerable.Range(0, reader.FieldCount).ToDictionary(i => reader.GetName(i), i=> reader.GetValue(i).ToString());
我从这个 * 问题中找到了指导:convert dataReader to Dictionary
【讨论】:
它已经是IDataRecord。
这应该为您提供与字典相同的访问权限(按键)。由于行通常不会有超过几列,因此查找的性能应该没有那么不同。唯一重要的区别是“有效负载”的类型,即使在那里你的字典也必须使用对象作为值类型,所以我给 IDataRecord 一个优势。
【讨论】:
GetValues 方法接受并放入一维数组中的所有值。
这有帮助吗?
【讨论】: