【发布时间】:2020-06-07 16:29:59
【问题描述】:
我需要从 DetelleHora 类型的对象列表创建一个 DataTable。 This post explains how to accomplish it,为 DetalleHora 的每个属性创建一列。
我面临的问题是 DetalleHora 的属性之一是 Hora 类型的对象列表,将包含未定义数量的项目(这就是为什么我不能这样做this),并且我无法遍历此列表,以便生成的 DataTable 包含每个项目的列。
这是 DetalleHora 类定义:
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; }
}
这是 Hora 类定义:
public class Hora
{
public int IdTipoHora { get; set; }
public string Tipo { get; set; }
public double Cantidad { get; set; }
}
这就是我正在做的事情(根据以下链接之一):
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;
}
我正在寻找一种方法来确定给定属性是否是特定类型对象的列表,但以下方法似乎都不适合我:
【问题讨论】:
-
如果
prop是一个集合,如何为List<Hora> Horas创建新的DataTable并将数据添加到此数据表中。 -
问题是我无法确定
prop是否是一个集合:( -
是的,你可以点赞:
if ((Props[i].GetValue(item, null) is IList list)) {//use list here},你也可以在这里ListToDataTablerecurisvely 在另一个里面构建dataTable。第二种解决方案:像 array 一样声明 Horas 并使用Props[i].PropertyType.IsArray