Skip to content

Instantly share code, notes, and snippets.

@mrkodssldrf
Created October 17, 2013 12:25
Show Gist options
  • Save mrkodssldrf/7023997 to your computer and use it in GitHub Desktop.
Save mrkodssldrf/7023997 to your computer and use it in GitHub Desktop.
Convert SQL Datareader to List<T> C#
public List<T> Query<T>(string query) where T:new()
{
List<T> res = new List<T>();
MySqlCommand q = new MySqlCommand(query, this.db);
MySqlDataReader r = q.ExecuteReader();
while (r.Read())
{
T t = new T();
for (int inc = 0; inc < r.FieldCount; inc++)
{
Type type = t.GetType();
PropertyInfo prop = type.GetProperty(r.GetName(inc));
prop.SetValue(t, r.GetValue(inc), null);
}
res.Add(t);
}
r.Close();
return res;
}
@Tomamais
Copy link

Tomamais commented Aug 2, 2018

One small enhancement on line 14:

prop.SetValue(t, Convert.ChangeType(r.GetValue(inc), prop.PropertyType), null);

It will prevent System.ArgumentException for properties of different types

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment