AsEnumerable

using System.Collections.Generic;
using System.Data;


// A set of extension methods for IDataReader
public static class DataReaderExtensions
{
	// Enumerates through the reads in an IDataReader.
	public static IEnumerable<IDataRecord> AsEnumerable(this IDataReader reader)
	{
		while (reader.Read())
		{
			yield return reader;
		}
	}
}
Example:
			using (var connection = new SqlConnection("some connection string"))
			using (var command = new SqlCommand("select * from products", connection))
			{
				connection.Open();

				using (var reader = command.ExecuteReader())
				{
					var results = reader.AsEnumerable()
						.Select(record => new Product
									{
										Name = (string)record["product_name"],
										Id = (int)record["product_id"],
										Category = (string)record["product_category"]
									})
						.GroupBy(product => product.Category);
				}
			}

Description

Allows you to treat an IDataReader from a database query as enumerable so that you can perform LINQ operations on it.

Details

Double click on the code to select all.

 

;