Skip to content

Instantly share code, notes, and snippets.

@jknopp
Last active February 2, 2021 19:09
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jknopp/97d6cc659439f591748df32cbd642fa6 to your computer and use it in GitHub Desktop.
Save jknopp/97d6cc659439f591748df32cbd642fa6 to your computer and use it in GitHub Desktop.
Helpful DataRow/DataTable Extensions
public static class DataTableExtensions
{
public static List<T> ToList<T>(this DataTable table) where T : new()
{
IList<PropertyInfo> properties = typeof(T).GetProperties().ToList();
List<T> result = new List<T>();
foreach (var row in table.Rows)
{
var item = CreateItemFromRow<T>((DataRow)row, properties);
result.Add(item);
}
return result;
}
// Consider moving to DataRowExtensions class
private static T CreateItemFromRow<T>(DataRow row, IEnumerable<PropertyInfo> properties) where T : new()
{
if (properties == null) throw new ArgumentNullException(nameof(properties));
T item = new T();
foreach (var property in properties)
{
if (row.Table.Columns.Contains(property.Name))
{
if (property.PropertyType == typeof(DayOfWeek))
{
DayOfWeek day = (DayOfWeek)Enum.Parse(typeof(DayOfWeek), row[property.Name].ToString());
property.SetValue(item, day, null);
}
else
{
property.SetValue(item, row[property.Name] == DBNull.Value ? null : row[property.Name], null);
}
}
}
return item;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment