以 IEnumerable 形式返回列值
我有这个代码工作:
public IEnumerable<string> GetEmpNames()
{
var cmd = SqlCommand("select [EmpName] from [dbo].[Emp]");
using (var rdr = cmd.ExecuteReader())
while (rdr.Read())
yield return (string) rdr["EmpName"];
}
但是,我想知道是否有更好的(LINQish)方法,而不必诉诸收益回报。 (并且 LINQ to SQL 不是一个选项:))
I have this code working:
public IEnumerable<string> GetEmpNames()
{
var cmd = SqlCommand("select [EmpName] from [dbo].[Emp]");
using (var rdr = cmd.ExecuteReader())
while (rdr.Read())
yield return (string) rdr["EmpName"];
}
However, I'm wondering if there's a better (LINQish) way, not having to resort to yield return. (And LINQ to SQL is not an option :) )
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
http://msdn.microsoft.com/en-us/library/bb361109.aspx
http://msdn.microsoft.com/en-us/library/bb361109.aspx
你不应该那样做!您的阅读器需要尽快关闭。您不想在枚举期间保持其打开状态。最好只创建一个显式列表,然后返回该列表。
您可以通过强制转换在 DataReader 上使用 Linq 表达式:
但请注意,您需要调用 ToList(),否则当您尝试枚举时会收到错误,因为读取器已关闭。
编辑
对于 DataReader 打开时实际执行的操作,评论中似乎存在一些混乱。 来自 MSDN:
因此,您应该尽快关闭它以释放连接。
You should not do that! Your reader needs to be closed as soon as possible. you do not want to keep it open for the duration of the enumeration. It is better to just create an explicit list, and return that.
You can use Linq expressions on a DataReader by casting it:
But notice that you need to call ToList(), or you will get an error when you try to enumerate because the reader has already been closed.
Edit
There seems to be some confusion in the comments about what a DataReader actually does when it's open. From MSDN:
Therefore you should close it as soon as possible to free up the connection.