vendredi 7 avril 2017

Convert Generic List to DataTable when the generic has nested objects

So I have seen the code here:

public static DataTable ConvertToDataTable<T>(this IList<T> data)
{
    PropertyDescriptorCollection properties = 
        TypeDescriptor.GetProperties(typeof(T));
    DataTable table = new DataTable();
    foreach (PropertyDescriptor prop in properties)
        table.Columns.Add(prop.Name, Nullable.GetUnderlyingType(prop.PropertyType) ?? prop.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;
}

But the complication I run into is that the object I want to convert to a DataTable has an object inside it that I want to expand into separate columns. I tried specifying the type of the nested object (since calling prop.getChildProperties() will find subproperties will find subproperties for DateTime, etc) as a parameter:

public static DataTable ConvertToDataTable<T>(this IList<T> data, Type nestedClass)

and I can get the necessary column names as such:

if (prop.PropertyType == nestedClass)
    {
        PropertyDescriptorCollection subproperties = TypeDescriptor.GetProperties(nestedClass);
        foreach (PropertyDescriptor subprop in subproperties)
        {
            table.Columns.Add(subprop.Name, Nullable.GetUnderlyingType(subprop.PropertyType) ?? subprop.PropertyType);
        }
    }

But the problem now is how to get the values for this nested object. I can get the nested object when the method calls prop.GetValue(item) when the item is the nested object, but I can't get the values of the subproperties from here. I tried converting it to its class using (T) Convert.ChangeType(input, typeof(T)) but nestedClass is already a type, and even if I did create the correct object (so I could use its get methods) I'm not sure this would be the best way to get these values anyway.

Any help as to how I can loop through and get the values of the nested object would be appreciated.





Aucun commentaire:

Enregistrer un commentaire