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 填充数组(或数组列表)
基础教程推荐
- SonarQube C# 分析失败“不是指针的有效行偏移" 2022-01-01
- 如果条件可以为空 2022-01-01
- 在 VB6 或经典 ASP 中使用 .NET 2022-01-01
- C# 9 新特性——record的相关总结 2023-04-03
- Mono https webrequest 失败并显示“身份验证或解密失败" 2022-01-01
- 重新排序 WPF TabControl 中的选项卡 2022-01-01
- 将数据集转换为列表 2022-01-01
- 获取C#保存对话框的文件路径 2022-01-01
- 更新 Visual Studio 中的 DataSet 结构以匹配新的 SQL 数据库结构 2022-01-01
- 从 C# 控制相机设备 2022-01-01
