I have a generic func that takes a string of fields and selects them from an object using linq. However the output is not type of object but a subset of. So to convert this new List<subsetOfOriginal> to a DataTable, I cannot use list.GetType() because it will get me Original.
I have converted
Func<T, T> CreateSelectStatement<T>(string fields)
to
Func<T, S> CreateSelectStatement<T, S>(string fields)
because I don't want TResult to be of type T. Not sure if this is the correct way. This is the code I have at the moment and how it is invoked.
Func<T, S> CreateSelectStatement<T, S>(string fields)
{
var xParameter = Expression.Parameter(typeof(T), "o");
var xNew = Expression.New(typeof(T));
var bindings = fields.Split(',').Select(o => o.Trim())
.Select(o => {
var mi = typeof(T).GetProperty(o);
var xOriginal = Expression.Property(xParameter, mi);
return Expression.Bind(mi, xOriginal);
}
);
var xInit = Expression.MemberInit(xNew, bindings);
var lambda = Expression.Lambda<Func<T, S>>(xInit, xParameter);
return lambda.Compile();
}
and then to invoke it I'm using
CreateSelectStatement<SP_ProjectAnalysis_NP, dynamic>(columns)
Expected outcome should be the fields that are loading correctly but the type of the object is as if I used p => new { }. Currently I am getting object as the return type and trying to perform the following gets me 0 properties:
private static DataTable ToDataTable<T>(IList<T> list, string tableName = "table")
{
PropertyDescriptorCollection props = TypeDescriptor.GetProperties(typeof(T));
Dumpstatement to verify thelambdais what you expect? The code seems okay to me - but your usage perhaps not. If your callingExpression.New(typeof(T))then by definition the result will be of typeTand not typeS. I believedynamicis treated likeobjectfor Reflection, so you really need to haveFunc<T, T>. Also, what type is being passed into the returnedFunc? If it is already aTI don't see the point...Expression.New(typeof(S))and notT, you're right. So the user is selecting columns from a table arbitrarily and I wantSto dynamically become an object of the new class containing the new columns as properties. Because after that I am passing list ofSto an excel creator. I don't wantTbecauseTwill give me a lot of columns with null values then (the un-selected).DataTable?