Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Fill an array (or arraylist) from SqlDataReader

Tags:

c#

ado.net

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).

like image 865
ristonj Avatar asked Sep 02 '09 22:09

ristonj


People also ask

Is there anything faster than SqlDataReader in net?

Caching namespace. If you're doing purely data operations (as your question suggests), you could rewrite your code which is using the data to be T-SQL and run natively on SQL. This has the potential to be much faster, as you will be working with the data directly and not shifting it about.

How do I get data from ExecuteReader?

To retrieve data using a DataReader, create an instance of the Command object, and then create a DataReader by calling Command. ExecuteReader to retrieve rows from a data source.

What is SqlDataReader in Ado net?

ADO.NET SqlDataReader Class. This class is used to read data from SQL Server database. It reads data in forward-only stream of rows from a SQL Server database. it is sealed class so that cannot be inherited.

What is the use of SqlDataReader in C#?

The SqlDataReader is used to read a row of record at a time which is got using SqlCommand. It is read only, which means we can only read the record; it can not be edited. And also it is forward only, which means you can not go back to a previous row (record).


2 Answers

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(); 

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

like image 175
Pavel Minaev Avatar answered Oct 14 '22 13:10

Pavel Minaev


No, since SqlDataReader is a forward-only read-only stream of rows from a SQL Server database, the stream of rows will be looped through whether explicitly in your code or hidden in a framework implementation (such as DataTable's Load method).

It sounds like using a generic list and then returning the list as an array would be a good option. For example,

List<int> list = new List<int>();  using (SqlDataReader reader = cmd.ExecuteReader()) {     while (reader.Read())     {          list.Add(reader.GetInt32(0));     }     } return list.ToArray(); 

In response to your comment, calling ToArray() may be overhead, it depends. Do you need an array of objects to work with or would a generic collection (such as List<T> or ReadOnlyCollection<T>) be more useful?

like image 41
Russ Cam Avatar answered Oct 14 '22 14:10

Russ Cam