填写从SqlDataReader的一个数组(或ArrayList中) [英] Fill an array (or arraylist) from SqlDataReader

查看:536
本文介绍了填写从SqlDataReader的一个数组(或ArrayList中)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有一种方法来填充通过一个SqlDataReader(或任何其他C#ADO.NET对象)的数组,而无需通过所有项目循环?我有一个返回一列的查询,我想它放入一个字符串数组(或ArrayList中,或列表等)。

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 ,而不是明确的在你的code。

That said, the loop is still there, it's just hidden in Enumerable.Select, rather than being explicit in your code.

这篇关于填写从SqlDataReader的一个数组(或ArrayList中)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆