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í:

  1. /// <summary>  
  2. /// Extiende un metodo sobre el objeto Datatable para devolver un IList  
  3. /// </summary>  
  4. public static IList<T> ConvertTo<T>(this DataTable pDataTable) where T : new()
  5. {
  6.     PropertyInfo[] entityImportProperties = typeof(T).GetProperties();
  7.     IList<T> colEntityImportList = new List<T>();
  8.     if (pDataTable == null)
  9.         return null;
  10.     if (pDataTable.Rows.Count == 0)
  11.         return colEntityImportList;
  12.     foreach (DataRow actualRow in pDataTable.Rows)
  13.     {
  14.         T objNewImportEntity = new T();
  15.         foreach (PropertyInfo propertyEntityImport in entityImportProperties)
  16.             if (propertyEntityImport.CanRead)
  17.                 for (int i = 0; i <= pDataTable.Columns.Count - 1; i++)
  18.                     if (pDataTable.Columns[i].ColumnName == propertyEntityImport.Name)
  19.                         if (actualRow[propertyEntityImport.Name] == null)
  20.                         {
  21.                             if (actualRow[propertyEntityImport.Name] == DBNull.Value)
  22.                                 propertyEntityImport.SetValue(objNewImportEntity, null, null);
  23.                             else
  24.                                 propertyEntityImport.SetValue(objNewImportEntity, actualRow[propertyEntityImport.Name], null);
  25.                             break;
  26.                         }
  27.         colEntityImportList.Add(objNewImportEntity);
  28.     }
  29.     return colEntityImportList;
  30.  
  31.     DataTable vSystemModulesTable = SystemManager.GetDataTable();
  32.     IList<SystemModule> vColSystem = vSystemModulesTable.ConvertTo<SystemModule>();
  33. }

Y se usa, de esta manera:

  1. DataTable vSystemModulesTable = SystemManager.GetDataTable();
  2. IList<SystemModule> vColSystem = vSystemModulesTable.ConvertTo<SystemModule>();

Populares!

- Copyright © - Oubliette - -Metrominimalist- Powered by Blogger - Designed by Johanes Djogan -