samedi 29 juin 2019

Transform IEnumerable to DataTable to its primitive types

I have an IEnumerable of Clients and the fields in the class Client are:

    public string Name { get; set; }
    public int Age { get; set; }
    public Town Hometown { get; set; }

And the fields in the class Hometown are:

    public string TownName { get; set; }
    public double Population { get; set; }
    public double Mortality{ get; set; }

The goal is to generate a generic method that can receive as input an IEnumerable and generate a DataTable with the primitive types of the particular class. In this example, it would be the following columns: Name, Age, TownName, Population and Morality.

I tried the below code:

    public DataTable TransformIEnumerableToDataTable<T>(IEnumerable<T> IEnumerableTable)
    {
        var props = typeof(T).GetProperties();

        foreach (PropertyInfo prop in props)
        {
            // here I don't know how I can get the properties of some properties
        }

        var dt = new DataTable();
        dt.Columns.AddRange(
          props.Select(p => new DataColumn(p.Name, Nullable.GetUnderlyingType(p.PropertyType) ?? p.PropertyType)).ToArray()
        );

        IEnumerableTable.ToList().ForEach(
          i => dt.Rows.Add(props.Select(p => p.GetValue(i, null)).ToArray())
        );

        return dt;
    }

The output, without the foreach statement, gives me a DataTable with the following columns: Name, Age and Hometown. However, I expect the output to have the primitive data types of hometown and not the hometown object itself.





Aucun commentaire:

Enregistrer un commentaire