Home > Backend Development > C++ > How to Easily Convert a DataReader to a List?

How to Easily Convert a DataReader to a List?

DDD
Release: 2025-01-16 22:21:16
Original
271 people have browsed it

How to Easily Convert a DataReader to a List?

Efficiently convert DataReader to List

DataReader is convenient for storing data, but sometimes it is necessary to process data in other formats (such as lists). Converting a DataReader to a strongly typed list, like List, can be cumbersome, but it doesn't have to be.

One way to simplify the process is to create an extension method to handle the conversion. 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>
Copy after login

This method takes a Func that defines how to convert each row of the DataReader into an instance of type T. You can then use LINQ's ToList() method to convert the result to a List.

Another approach is to create a method in the target type (Customer) that converts from DataReader. For example:

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

Using this method you can simply retrieve the List using the following code:

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

The above is the detailed content of How to Easily Convert a DataReader to a List?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template