ExtensionMethod.NET Home of 880 C#, Visual Basic, F# and Javascript extension methods

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>();

Author: UlisexXx

Submitted on: 21 nov. 2023

Language: csharp

Type: System.Data

Views: 1327