IDataReader - ToDataTable
An IDataReader extension method that converts the @this to a data table.
public static void Main() { const string sql = "SELECT 1 AS IntColumn, 'FizzBuzz' AS StringColumn"; using (var conn = new SqlConnection(FiddleHelper.GetConnectionStringSqlServer())) { conn.Open(); using (DbCommand command = conn.CreateCommand()) { command.CommandText = sql; using (IDataReader reader = command.ExecuteReader()) { //C# Extension Method: IDataReader - ToDataTable DataTable result = reader.ToDataTable(); Console.WriteLine(result.Rows[0][0]); Console.WriteLine(result.Rows[0][1]); } } } }
View Source
using System.Data; public static partial class Extensions { /// <summary> /// An IDataReader extension method that converts the @this to a data table. /// </summary> /// <param name="this">The @this to act on.</param> /// <returns>@this as a DataTable.</returns> public static DataTable ToDataTable(this IDataReader @this) { var dt = new DataTable(); dt.Load(@this); return dt; } }