// Collection of code snippets by Arne Vajhøj // (likely posted to comp.os.vms/INFO-VAX, INFO-TPU, MACRO32, eksperten.dk, newz.dk, LinkedIn or other place sometime between 1990 and now) using System; using System.Collections.Generic; using System.Data; using System.Linq; using MySql.Data.MySqlClient; namespace QueryUtilDemo { public static class QueryUtil { public static List ToList(this IDbCommand sel, Func cb) { List res = new List(); using(IDataReader rdr = sel.ExecuteReader()) { while(rdr.Read()) { res.Add(cb(rdr)); } } return res; } } public class T1 { public int F1 { get; set; } public string F2 { get; set; } } public class Program { private static void Dump(List lst) { foreach(T1 o in lst) { Console.WriteLine("{0} {1}", o.F1, o.F2); } } public static List Traditional(IDbConnection con) { List res = new List(); using(IDbCommand sel = con.CreateCommand()) { sel.CommandText = "SELECT f1,f2 FROM t1"; using(IDataReader rdr = sel.ExecuteReader()) { while(rdr.Read()) { res.Add(new T1 { F1 = (int)rdr["f1"], F2 = (string)rdr["f2"] }); } } } return res; } private static void TestTraditional(IDbConnection con) { Dump(Traditional(con)); } public static List Wrapped(IDbConnection con) { using(IDbCommand sel = con.CreateCommand()) { sel.CommandText = "SELECT f1,f2 FROM t1"; return sel.ToList(rdr => new T1 { F1 = (int)rdr["f1"], F2 = (string)rdr["f2"] }); } } private static void TestWrapped(IDbConnection con) { Dump(Wrapped(con)); } public static void Main(string[] args) { using(IDbConnection con = new MySqlConnection("Server=localhost;Database=Test;user=root;password=;")) { con.Open(); TestTraditional(con); TestWrapped(con); } } } }