Publicado por: Carlos
lunes, febrero 07, 2011
- /// <summary>
- /// Exiende un metodo sobre una Lista para devolver un Dataset
- /// con las columnas del objeto de la lista
- /// </summary>
- /// <typeparam name="T"></typeparam>
- /// <param name="pList"></param>
- /// <returns></returns>
- public static DataTable ConvertTo<T>( this IList<T> pList )
- {
- DataTable table = CreateTable<T>();
- Type entityType = typeof( T );
- PropertyDescriptorCollection properties = TypeDescriptor.GetProperties( entityType );
- foreach ( T item in pList )
- {
- DataRow row = table.NewRow();
- foreach ( PropertyDescriptor prop in properties )
- row[prop.Name] = prop.GetValue( item );
- table.Rows.Add( row );
- }
- return table;
- }
- /// <summary>
- /// Devuelve un item de tipo T
- /// </summary>
- /// <typeparam name="T"></typeparam>
- /// <param name="pRow">The p row.</param>
- /// <returns></returns>
- private static T CreateItem<T>( DataRow pRow )
- {
- T obj = default( T );
- if ( pRow == null )
- return obj;
- obj = Activator.CreateInstance<T>();
- foreach ( DataColumn column in pRow.Table.Columns )
- {
- PropertyInfo prop = obj.GetType().GetProperty( column.ColumnName );
- object value = pRow[column.ColumnName];
- prop.SetValue( obj, value, null );
- }
- return obj;
- }
- /// <summary>
- /// Crea un DataTable con columnas del tipo T
- /// </summary>
- /// <typeparam name="T"></typeparam>
- /// <returns></returns>
- private static DataTable CreateTable<T>()
- {
- Type entityType = typeof( T );
- DataTable table = new DataTable( entityType.Name );
- PropertyDescriptorCollection properties = TypeDescriptor.GetProperties( entityType );
- foreach ( PropertyDescriptor prop in properties )
- table.Columns.Add( prop.Name, prop.PropertyType );
- return table;
- }
Publicar un comentario