ExtensionMethod.NET Home of 880 C#, Visual Basic, F# and Javascript extension methods

AsEnumerable

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

Source

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);
				}
			}

Author: James Michael Hare

Submitted on: 20 okt. 2010

Language: C#

Type: System.Data.IDataReader

Views: 8643