Home >Backend Development >C++ >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
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
<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
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!