dimanche 7 mai 2017

Datatable from List

I have downloaded data that is contained in a List<Row> Rows like this:

class Row
{
    string[] Items { get; set; }
    public Row(string[] Items)
    {
        this.Items = Items;
    }
}

The rows are basically comma delimited entries (.csv)

using (var reader = new StreamReader(spreadSheetStream))          
{
    string header = reader.ReadLine(); //This is the header
    Rows.Add(new Row(header.Split(',')));

    while (!reader.EndOfStream)
    {
        string tickerInfo = reader.ReadLine();  //This is a data entry                                             
        Rows.Add(new Row(tickerInfo.Split(',')));                        
    }
}

I convert the List into a Datatable like this

DataTable historicalDataTable = ToDataTable<Row>(Rows);

The first element of List<Row> Rows contains the names of the columns, seven of them. Then each element thereafter is an actual data element.

public static DataTable ToDataTable<T>(List<T> items)
{
    DataTable dataTable = new DataTable(typeof(T).Name);

    //Get all the properties
    PropertyInfo[] Props = typeof(T).GetProperties(BindingFlags.Public | BindingFlags.Instance);
    foreach (PropertyInfo prop in Props)
    {
        //Setting column names as Property names
        dataTable.Columns.Add(prop.Name);
    }
    foreach (T item in items)
    {
        var values = new object[Props.Length];
        for (int i = 0; i < Props.Length; i++)
        {
            //inserting property values to datatable rows
            values[i] = Props[i].GetValue(item, null);
        }
        dataTable.Rows.Add(values);
    }
    //put a breakpoint here and check datatable
    return dataTable;
}

When I try to write out the contents of the table, I see the right number of rows, but there is nothing in ItemArray

foreach (DataRow dataRow in historicalDataTable.Rows)
{
    Console.WriteLine(dataRow.ToString());
    foreach (var item in dataRow.ItemArray)
    {
        Console.WriteLine(item);
    }
}





Aucun commentaire:

Enregistrer un commentaire