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 填充数组(或数组列表)


- 带有服务/守护程序应用程序的 Microsoft Graph CSharp SDK 和 OneDrive for Business - 配额方面返回 null 2022-01-01
- 如何用自己压缩一个 IEnumerable 2022-01-01
- C# 中多线程网络服务器的模式 2022-01-01
- WebMatrix WebSecurity PasswordSalt 2022-01-01
- Web Api 中的 Swagger .netcore 3.1,使用 swagger UI 设置日期时间格式 2022-01-01
- C#MongoDB使用Builders查找派生对象 2022-09-04
- MoreLinq maxBy vs LINQ max + where 2022-01-01
- 在哪里可以找到使用中的C#/XML文档注释的好例子? 2022-01-01
- 输入按键事件处理程序 2022-01-01
- 良好实践:如何重用 .csproj 和 .sln 文件来为 CI 创建 2022-01-01