有没有一种简单的方法可以将 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
}
谢谢
You can use 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));
}
我仍然不确定为什么您需要从一种类型的集合到另一种类型的这种特殊转换。
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
它已经是一个IDataRecord
.
这应该为您提供与字典几乎相同的访问权限(按键)。由于行通常不会超过几列,因此查找的性能应该没有那么不同。唯一重要的区别是“有效负载”的类型,即使在那里你的字典也必须使用对象作为值类型,所以我给 IDataRecord 的优势。
GetValues 方法接受并放入一维数组中的所有值。
这有帮助吗?