Skip to content

Instantly share code, notes, and snippets.

@amarraja
Created July 9, 2010 16:53
Show Gist options
  • Save amarraja/469701 to your computer and use it in GitHub Desktop.
Save amarraja/469701 to your computer and use it in GitHub Desktop.
/* Simple utility to take some of the pain of working with a datareader */
public static class DataReaderExtensions
{
public static IList<T> ToTypedList<T>(this SqlDataReader dr) where T : class, new()
{
var list = new List<T>();
if (!dr.HasRows)
return list;
var propertyMap = new Dictionary<string, PropertyInfo>();
for (int x = 0; x < dr.FieldCount; x++)
{
string columnName = dr.GetName(x);
var property = typeof (T).GetProperties()
.Where(t => t.Name.Equals(columnName, StringComparison.OrdinalIgnoreCase))
.SingleOrDefault();
if (property != null)
{
propertyMap.Add(columnName, property);
}
}
while(dr.Read())
{
T t = new T();
foreach (var propertyInfo in propertyMap)
{
object columnValue = dr[propertyInfo.Key];
if (columnValue != DBNull.Value)
propertyInfo.Value.SetValue(t, columnValue, null);
}
list.Add(t);
}
return list;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment