ToListado
Convierte un DataTable a un Listado de un Tipo Especifico.
Source
public static List<T> ToListado<T>(this DataTable source) {
if(source != null && source.Rows.Count > 0) {
return (
from DataRow lDtFila in source.Rows
select lDtFila.ToItem<T>()
).ToList();
}
else {
return null;
}
}
public static T ToItem<T>(this DataRow source) {
var lTypeDef = typeof(T);
var lItem = Activator.CreateInstance<T>();
foreach(DataColumn lDtColumna in source.Table.Columns) {
foreach(var lPropInfo in lTypeDef.GetProperties()) {
if(lPropInfo.Name == lDtColumna.ColumnName) {
if(source[lDtColumna.ColumnName] != DBNull.Value)
lPropInfo.SetValue(lItem, source[lDtColumna.ColumnName], null);
break;
}
}
}
return lItem;
}
Example
DataTable DtTabla = new DataTable();
List<Person> Listado = DtTabla.ToListado<Person>();