Convertir List<> a DataTable C Sharp

El siguiente método sirve para convertir nuestras listas de Objetos en un DataTable de manera mas simple y rápida.


public DataTable ConvertToDataTable(IList data)
{
   PropertyDescriptorCollection propiedades = TypeDescriptor.GetProperties(typeof(T));
   DataTable table = new DataTable();

   foreach (PropertyDescriptor prop in propiedades){
       table.Columns.Add(prop.Name,Nullable.GetUnderlyingType(prop.PropertyType)?? rop.PropertyType);
   }
   foreach (T item in data)
   {
      DataRow row = table.NewRow();
         foreach (PropertyDescriptor prop in properties){
            row[prop.Name] = prop.GetValue(item) ?? DBNull.Value;
         }
      table.Rows.Add(row);
    }
    return table;

} 

Saludos

También te podría gustar...

3 Respuestas

  1. Heiner barbosa dice:

    OMG

  2. Manuel dice:

    Excelente funcion (metodo) !! Thanxs so Much!!

  3. Leodev dice:

    ESPECTACULAR!! Gracias!

Deja una respuesta

Tu dirección de correo electrónico no será publicada.