mercredi 20 février 2019

Calling extension method from dynamic list

I am creating a type using reflection...

Type type = Type.GetType("Book");

I am then invoking a method dynamically...

MethodInfo method = typeof(DataHelper).GetMethod("GetTableData");
MethodInfo generic = method.MakeGenericMethod(type);
var parameters = new object[] {...};
dynamic data = generic.Invoke(this, parameters);

The method returns data, and looks like this...

public static IEnumerable<T> GetTableData<T>(parameters)
{
...
}

From the Dynamic data, I want to convert this to a list and call an extension method to convert the List into a DataTable.

I have tried the following, which fails when calling .ToDataTable:

var x = Enumerable.ToList(data);
x.ToDataTable().BulkCopyDataTable(settings, booName);

I have also tried:

var tl = GetTypedList(type);
            foreach (var d in x)
            {
                tl.Add(d);
            }

var y = tl.ToDataTable(); // compilaer error.

private static IList GetTypedList(Type t)
        {
            var listType = typeof(List<>);
            var constructedListType = listType.MakeGenericType(t);
            var instance = Activator.CreateInstance(constructedListType);
            return (IList) instance;
        }

The Extension method I am trying to call is:

public static DataTable ToDataTable<T>(this IList<T> data)
        {
            var properties = TypeDescriptor.GetProperties(typeof(T));
            var table = new DataTable();
            foreach (PropertyDescriptor prop in properties)
                table.Columns.Add(prop.Name, Nullable.GetUnderlyingType(prop.PropertyType) ?? prop.PropertyType);

            foreach (var item in data)
            {
                var row = table.NewRow();
                foreach (PropertyDescriptor prop in properties)
                    row[prop.Name] = prop.GetValue(item) ?? DBNull.Value;
                table.Rows.Add(row);
            }


            return table;
        }

Any pointers on where this is going wrong?





Aucun commentaire:

Enregistrer un commentaire