Home >Backend Development >C++ >How Can I Efficiently Convert a DataReader into a List in .NET?

How Can I Efficiently Convert a DataReader into a List in .NET?

Susan Sarandon
Susan SarandonOriginal
2025-01-16 22:17:09982browse

How Can I Efficiently Convert a DataReader into a List in .NET?

Process data efficiently: Convert DataReader to List

When processing data in a .NET environment, you may want to convert a DataReader (a data stream that only reads forward) into a more manageable format, such as a List. This transformation allows you to access and process structured data more efficiently.

Solution: Extension methods

One way to convert is to use extension methods. An example is as follows:

<code class="language-csharp">public static IEnumerable<T> Select<T>(this IDataReader reader,
                                       Func<IDataReader, T> projection)
{
    while (reader.Read())
    {
        yield return projection(reader);
    }
}</code>

This extension method allows you to use projection functions to select data from a DataReader and convert it to an IEnumerable.

Examples of usage

To convert data to List you can use the following code:

<code class="language-csharp">using (IDataReader reader = ...)
{
    List<Customer> customers = reader.Select(r => new Customer {
        CustomerId = r["id"] is DBNull ? null : r["id"].ToString(),
        CustomerName = r["name"] is DBNull ? null : r["name"].ToString()
    }).ToList();
}</code>

This example converts the rows in the DataReader into a list of Customer objects.

Alternative: specialized methods for entity types

Alternatively, you can create a dedicated static method in the Customer entity:

<code class="language-csharp">public static Customer FromDataReader(IDataReader reader) { ... }</code>

This method is responsible for creating a Customer object based on the data in the DataReader.

Using this method you can simplify the conversion process:

<code class="language-csharp">using (IDataReader reader = ...)
{
    List<Customer> customers = reader.Select<Customer>(Customer.FromDataReader)
                                     .ToList();
}</code>

Through these techniques, you can efficiently convert the data in DataReader into List, thereby leveraging the power of LINQ for further data manipulation and processing.

The above is the detailed content of How Can I Efficiently Convert a DataReader into a List in .NET?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn