【发布时间】:2013-09-25 19:13:48
【问题描述】:
我从 SQL Server 获取动态列数的查询结果,列名可变。 如何将 datareader 的结果转换为通用列表 List ?
public ? getItems(string orderId)
{
SqlConnection sqlConn = new SqlConnection(conn);
SqlCommand command = new SqlCommand();
SqlDataReader reader;
try
{
sqlConn.Open();
command.Connection = sqlConn;
command.CommandText = "usp_get_orders";
command.CommandType = CommandType.StoredProcedure;
command.Parameters.Add(new SqlParameter("@Id", orderId)));
SqlDataReader reader = command.ExecuteReader();
while (reader.Read())
{
?
}
reader.Close();
}
catch (Exception exp)
{
}
finally
{
command.Dispose();
command1.Dispose();
sqlConn.Close();
sqlConn.Dispose();
}
return ?;
}
【问题讨论】:
-
给我们看一些代码,例如你如何创建阅读器
-
如何以列表形式返回列数和列名可变的动态结果?
-
你不能,真的,至少不能以一种有意义的方式。这里最好的选择是改用
DataTable之类的东西。 -
@Servy 因为你可以,请不要
DataTable,DataTables 是垃圾(慢) -
@Ela 他们并没有那么慢。它们可能比其他选项慢,因为它们为您做了很多。在许多情况下,您并不需要他们提供给您的太多东西,但这似乎是 OP 确实需要从
DataTable获得的一些通用性的情况,因此它实际上可能具有与另一种解决方案相当的性能。我的猜测是,它会比您的答案[略微] 快(但内存密集度显着减少),例如,相对而言,创建大量小型词典的成本很高。
标签: c# dynamic arraylist ado.net generic-list