paulyoder / LinqToExcel

Use LINQ to retrieve data from spreadsheets and csv files

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Dynamic AddTransformation Question

z-jack opened this issue · comments

commented

I met a confuse problem when I use the AddTransformation method. The problem is, in brief, I need to bind the transformation dynamically, which means the property name can be known only in runtime. And therefore I cannot invoke the method as the example shown:

excel.AddTransformation<Model>(x => x.property, x => SomeOperate(x));

In fact, I need a method that like this:

excel.AddTransformation<Model>(propertyName, x => SomeOperate(x));

Thanks for help!

commented

I use a very tricky way to solve this problem:

private Expression<Func<T, object>> GenerateExpression<T>(string name)
 {
    var arg = System.Linq.Expressions.Expression.Parameter(typeof(T), "x");
    var body = System.Linq.Expressions.Expression.Convert(System.Linq.Expressions.Expression.PropertyOrField(arg, name),
        typeof(object));
    var lambda = System.Linq.Expressions.Expression.Lambda<Func<T, object>>(body, arg);
    return lambda;
}

Can you provide a more complete example to better demonstrate your use-case?

commented

In order to decoupling, the properties of class which are going to have a transformation are obtained through reflection. Therefore, the property name is easier to obtain than lambda expression. For example,

class Model{
    int a {get; set;}
    int b {get;set;}
    ...
}

void BindFunction () {
    var list = typeof(Model).GetProperties();
    foreach ( var prop in list) {
        excel.AddTransformation<Model>(prop, ConvertStringToInt);
    }
}