Converting a DataTable to List

Converting a DataTable to List

 

 

public static List<T> ToList<T>(this DataTable table) where T : new()
{
      List<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;
    }
    private static T CreateItemFromRow<T>(DataRow row, List<PropertyInfo> properties) where T : new()
    {
      T item = new T();
      foreach (var property in properties)
      {
        if (row.Table.Columns.Contains(property.Name))
        {
          if (row[property.Name] != DBNull.Value)
            property.SetValue(item, row[property.Name], null);
        }
      }
      return item;
}