有没有一种简单的方法将SqlDataReader当前行的所有列转换为字典?
using (SqlDataReader opReader = command.ExecuteReader())
{
// Convert the current row to a dictionary
}
谢谢
有没有一种简单的方法将SqlDataReader当前行的所有列转换为字典?
using (SqlDataReader opReader = command.ExecuteReader())
{
// Convert the current row to a dictionary
}
谢谢
你可以使用 LINQ:
return Enumerable.Range(0, reader.FieldCount)
.ToDictionary(reader.GetName, reader.GetValue);
有比这更简单的方法吗?
// 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);
- Cade Roux我在2016年3月9日遇到了这个问题,最终使用了SLaks所提供的答案。但是,我需要稍微修改一下:
dataRowDictionary = Enumerable.Range(0, reader.FieldCount).ToDictionary(i => reader.GetName(i), i=> reader.GetValue(i).ToString());
GetValues方法接受并将所有值放入一维数组中。
这有帮助吗?
它已经是一个IDataRecord
了。
这应该给你几乎与字典相同的访问权限(按键)。由于行通常不会有超过几个列,查找的性能应该没有太大差异。唯一重要的区别是“有效载荷”的类型,即使在那里,您的字典也必须使用对象作为值类型,因此我将优先考虑IDataRecord。
AddressOf
。 - SLaks