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
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>
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>
Using this method you can simply retrieve the List
<code class="language-csharp">using (IDataReader reader = ...) { List<Customer> customers = reader.Select<Customer>(Customer.FromDataReader) .ToList(); }</code>
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!