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


基础教程推荐
- 将 Office 安装到 Windows 容器 (servercore:ltsc2019) 失败,错误代码为 17002 2022-01-01
- rabbitmq 的 REST API 2022-01-01
- 如何在 IDE 中获取 Xamarin Studio C# 输出? 2022-01-01
- SSE 浮点算术是否可重现? 2022-01-01
- c# Math.Sqrt 实现 2022-01-01
- 如何激活MC67中的红灯 2022-01-01
- 有没有办法忽略 2GB 文件上传的 maxRequestLength 限制? 2022-01-01
- MS Visual Studio .NET 的替代品 2022-01-01
- 为什么Flurl.Http DownloadFileAsync/Http客户端GetAsync需要 2022-09-30
- 将 XML 转换为通用列表 2022-01-01