Convertir una lista generica List a un DataTable

Reciente tuve un proyecto donde decidí no utilizar mi fiel SQL Server, quería probar algo nuevo.. diferente. Así que me fui por el lado del movimiento NoSql y utilice RavenDB. Les puedo decir que es una gran herramienta para proyectos que no requieran ser relacionales, algo como esto.

Y mi duda surgió al momento de tener que hacer un reporte en  Reporting Services en modo local (rdlc) y poder conectar el reporte con los datos. Lo primero que vi es que el Api de RS tiene  la  siguiente propiedad en el Viewer

[sourcecode language=”csharp” collapse=”false”]
LocalReport.DataSources
[/sourcecode]

que es una lista de la clase ReportDataSource , a esta clase se le debe asignar un datasource para pasar la información al reporte , el problema viene por que la clase solo acepta DataTables no List.
Esto Fue lo que hice, implemente un método extensor para las List<T> que me las convierta a un datatable, lo que hago es que creo una tabla con las propiedades de la clase como columnas y les voy agregando un row por cada objeto de la colección, aquí el código:

[sourcecode language=”csharp”]
static class DataHelper
{
public static DataTable ToDataTable<T>(this IList<T> data)
{
PropertyDescriptorCollection props =
TypeDescriptor.GetProperties(typeof(T));
DataTable table = new DataTable();
for (int i = 0; i < props.Count; i++)
{
PropertyDescriptor prop = props[i];
table.Columns.Add(prop.Name, prop.PropertyType);
}
object[] values = new object[props.Count];
foreach (T item in data)
{
for (int i = 0; i < values.Length; i++)
{
values[i] = props[i].GetValue(item);
}
table.Rows.Add(values);
}
return table;
}
}
[/sourcecode]

Al final solo queda hacer esto:

[sourcecode language=”csharp”]
var source = new ReportDataSource("Entities_Paleta", paletas.ToDataTable());
//Agrego el datasource al ReportViewer
viewer.LocalReport.DataSources.Add(data);
[/sourcecode]

3 comments

  1. Shopping for a new or used car can be a difficult process if you
    do not know what you are doing. By educating yourself about
    car shopping before you head to the dealership, you
    can make things easier for yourself. The following tips can help your next shopping trip be more enjoyable.

  2. It’s actually a nice and helpful piece of info. I am glad that you shared this helpful information with us. Please keep us informed like this. Thanks for sharing.

Leave a comment

Your email address will not be published. Required fields are marked *