Fill an array (or arraylist) from SqlDataReader(从 SqlDataReader 填充数组(或数组列表))
问题描述
有没有一种方法可以通过 SqlDataReader(或任何其他 C# ADO.NET 对象)填充数组,而无需遍历所有项目?我有一个返回单列的查询,我想将其放入字符串数组(或 ArrayList 或 List 等)中.
Is there a way to fill an array via a SqlDataReader (or any other C# ADO.NET object) without looping through all the items? I have a query that is returning a single column, and I want to put that into a string array (or ArrayList, or List, etc).
推荐答案
有可能.在 .NET 2.0+ 中,SqlDataReader
继承自 DbDataReader
,后者实现了 IEnumerable
(非泛型).这意味着您可以使用 LINQ:
It is possible. In .NET 2.0+, SqlDataReader
inherits from DbDataReader
, which implements IEnumerable
(non-generic one). This means that you can use LINQ:
List<string> list = (from IDataRecord r in dataReader
select (string)r["FieldName"]
).ToList();
也就是说,循环仍然存在,它只是隐藏在 Enumerable.Select
中,而不是在您的代码中显式显示.
That said, the loop is still there, it's just hidden in Enumerable.Select
, rather than being explicit in your code.
这篇关于从 SqlDataReader 填充数组(或数组列表)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:从 SqlDataReader 填充数组(或数组列表)


基础教程推荐
- JSON.NET 中基于属性的类型解析 2022-01-01
- 首先创建代码,多对多,关联表中的附加字段 2022-01-01
- 经典 Asp 中的 ResolveUrl/Url.Content 等效项 2022-01-01
- 全局 ASAX - 获取服务器名称 2022-01-01
- 错误“此流不支持搜索操作"在 C# 中 2022-01-01
- 是否可以在 asp classic 和 asp.net 之间共享会话状态 2022-01-01
- 从 VS 2017 .NET Core 项目的发布目录中排除文件 2022-01-01
- 在 VS2010 中的 Post Build 事件中将 bin 文件复制到物 2022-01-01
- 如何动态获取文本框中datagridview列的总和 2022-01-01
- 将事件 TextChanged 分配给表单中的所有文本框 2022-01-01