Publicado por: Carlos
martes, febrero 01, 2011
Necesito pasar el contenido de un Datatable a un IList de tipo T, aprovechando la facilidad de extender clases, quedo así:
- /// <summary>
- /// Extiende un metodo sobre el objeto Datatable para devolver un IList
- /// </summary>
- public static IList<T> ConvertTo<T>(this DataTable pDataTable) where T : new()
- {
- PropertyInfo[] entityImportProperties = typeof(T).GetProperties();
- IList<T> colEntityImportList = new List<T>();
- if (pDataTable == null)
- return null;
- if (pDataTable.Rows.Count == 0)
- return colEntityImportList;
- foreach (DataRow actualRow in pDataTable.Rows)
- {
- T objNewImportEntity = new T();
- foreach (PropertyInfo propertyEntityImport in entityImportProperties)
- if (propertyEntityImport.CanRead)
- for (int i = 0; i <= pDataTable.Columns.Count - 1; i++)
- if (pDataTable.Columns[i].ColumnName == propertyEntityImport.Name)
- if (actualRow[propertyEntityImport.Name] == null)
- {
- if (actualRow[propertyEntityImport.Name] == DBNull.Value)
- propertyEntityImport.SetValue(objNewImportEntity, null, null);
- else
- propertyEntityImport.SetValue(objNewImportEntity, actualRow[propertyEntityImport.Name], null);
- break;
- }
- colEntityImportList.Add(objNewImportEntity);
- }
- return colEntityImportList;
- DataTable vSystemModulesTable = SystemManager.GetDataTable();
- IList<SystemModule> vColSystem = vSystemModulesTable.ConvertTo<SystemModule>();
- }
Y se usa, de esta manera:
- DataTable vSystemModulesTable = SystemManager.GetDataTable();
- IList<SystemModule> vColSystem = vSystemModulesTable.ConvertTo<SystemModule>();
Publicar un comentario