SqlDataReader – 如何将当前行转换为字典
有没有一种简单的方法将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 dict = new Dictionary(); for( int lp = 0 ; lp < opReader.FieldCount ; lp++ ) { dict.Add(opReader.GetName(lp), opReader.GetValue(lp)); }
我仍然不确定为什么你需要从一种类型的集合到另一种集合的这种特殊转换。
我在2016年3月9日遇到了这个问题,最后使用了SLaks提供的答案。 但是,我需要稍微修改它为:
dataRowDictionary = Enumerable.Range(0, reader.FieldCount).ToDictionary(i => reader.GetName(i), i=> reader.GetValue(i).ToString());
我从StackOverflow问题中找到了指导: 将dataReader转换为Dictionary
它已经是一个IDataRecord
。
这应该给你几乎与字典相同的访问权限(按键)。 由于行通常不会有多个列,因此查找的性能不应该那么不同。 唯一重要的区别是“有效负载”的类型,即使你的字典必须使用对象作为值类型,所以我给IDataRecord边缘。
GetValues方法接受并放入1D数组中的所有值。
这有帮助吗?