0

I'm trying to make a helper method that creates a dynamic selector using expression tree.

The objective would be converting this selector into an expression tree.

var list = new User[0].AsQueryable();
var q = list.Select(u => new { User = u, Address = "Address X", Fax = "Fax Y" });

In the expression tree visualizer it shows something like:

Visualizer

Here is what I have tried so far:

var userParam = Expression.Parameter(typeof(User), "u");
var obj = new { User = new User(), Address = string.Empty, Fax = string.Empty };
var q = list.Select(DynamicSelect(obj, userParam));

static Expression<Func<User, T>> DynamicSelect<T>(T obj, ParameterExpression userParam)
{
    var user = Expression.Lambda<Func<User, User>>(/* ?? stuck here */, userParam);
    var newExpression = Expression.New(
        typeof(T).GetConstructor(new []{typeof(User), typeof(string), typeof(string)}), 
        user,
        Expression.Constant("Address X"),
        Expression.Constant("Fax Y"),
    );

    return Expression.Lambda<Func<User, T>>(newExpression, userParam);
}
tsuta
  • 357
  • 4
  • 12
  • Your code seems to be trying to create something like `u => new { User = u => /* stuck here */, Address = "Address X", Fax = "Fax Y" }`. Why are you doing that? Why are you trying to use a lambda inside a lambda, that doesn't make any sense to me. – svick Sep 30 '14 at 10:51

1 Answers1

1

You don't need a lambda inside a lambda here, you can just use userParam directly:

static Expression<Func<User, T>> DynamicSelect<T>(T obj, ParameterExpression userParam)
{
    var newExpression = Expression.New(
        typeof(T).GetConstructor(new []{typeof(User), typeof(string), typeof(string)}), 
        userParam,
        Expression.Constant("Address X"),
        Expression.Constant("Fax Y"),
    );

    return Expression.Lambda<Func<User, T>>(newExpression, userParam);
}

Also, I don't understand why is userParam a parameter of the method, I would create it inside the method.

svick
  • 236,525
  • 50
  • 385
  • 514
  • Omg, I never thought passing the param will just work, I accept the param as parameter to prevent problem like [in my previous question](http://stackoverflow.com/questions/25842275/combining-andalso-the-parameter-foo-was-not-bound-in-the-specified-linq-to-ent) – tsuta Sep 30 '14 at 10:58