public static DataTable GetDataTableFromIList<T>(List<T> aIList)
{
DataTable _returnTable = new DataTable();
if (aIList.Count > 0)
{
//Creates the table structure looping in the in the first element of the list
object _baseObj = aIList[0];
Type objectType = _baseObj.GetType();
PropertyInfo[] properties = objectType.GetProperties();
DataColumn _col;
foreach (PropertyInfo property in properties)
{
_col = new DataColumn();
_col.ColumnName = (string)property.Name;
_col.DataType = property.PropertyType;
_returnTable.Columns.Add(_col);
}
//Adds the rows to the table
DataRow _row;
foreach (object objItem in aIList)
{
_row = _returnTable.NewRow();
foreach (PropertyInfo property in properties)
{
_row[property.Name] = property.GetValue(objItem, null);
}
_returnTable.Rows.Add(_row);
}
}
return _returnTable;
}