问题描述
有没有一种方法可以通过 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 填充数组(或数组列表)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!