I need to create a DataTable from a List of objects of type DetalleHora. This post explains how to accomplish it, creating a column for each property of DetalleHora.
The problem I am facing is that one the properties of DetalleHora is a List of objects of type Hora, which will contain an undefined number of items (that's why I can't do this), and I can't get to iterate through this List so that the resulting DataTable contains a column for each one of the items.
This is the DetalleHora class definition:
class DetalleHora
{
public int Id { get; set; }
public string Fecha { get; set; }
public string Solicitante { get; set; }
public string Orden { get; set; }
public string DMR { get; set; }
public string Descripcion { get; set; }
public string Operario { get; set; }
public string Entrada { get; set; }
public string Salida { get; set; }
public List<Hora> Horas { get; set; }
public double TotalHoras { get; set; }
public string FirmaSolicitante { get; set; }
public int NumeroSemana { get; set; }
}
This is the Hora class definition:
public class Hora
{
public int IdTipoHora { get; set; }
public string Tipo { get; set; }
public double Cantidad { get; set; }
}
This is what I've doing (per one of the links below):
public DataTable ListToDataTable<T>(List<T> items)
{
DataTable dataTable = new DataTable(typeof(T).Name);
//Get all the properties
PropertyInfo[] Props = typeof(T).GetProperties(BindingFlags.Public | BindingFlags.Instance);
foreach (PropertyInfo prop in Props)
{
//Setting column names as Property names
// ******* I need a new column for each item in the List<Hora> Property
dataTable.Columns.Add(prop.Name);
}
foreach (T item in items)
{
var values = new object[Props.Length];
for (int i = 0; i < Props.Length; i++)
{
//inserting property values to datatable rows
// *********** BUT THIS WON'T WORK WHEN PROPERTY IS A LIST<T>
// I need a new column for each of the items in the List<Hora> Property
values[i] = Props[i].GetValue(item, null);
}
dataTable.Rows.Add(values);
}
//put a breakpoint here and check datatable
return dataTable;
}
I've looking for a way to determine if a given property is a List of a specific type of object, but none of the folowing approaches seemed to work for me: