0

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?

Christian Phillips
  • 18,399
  • 8
  • 53
  • 82
  • I'm guessing you'll need to call it as a static method? `YourExtensionsClass.ToDataTable(list)` – canton7 Feb 20 '19 at 14:19
  • Possible duplicate of [Extension method and dynamic object](https://stackoverflow.com/questions/5311465/extension-method-and-dynamic-object) – canton7 Feb 20 '19 at 14:20

0 Answers0