Combining multiple expressions to dynamically crea

2019-04-02 11:59发布

问题:

Given an input of two expressions, e.g.:

Expression<Func<Customer,string>> nameExpression = x=>x.Name;
Expression<Func<Customer,string>> nameExpression = x=>x.MarketSegment.Name;

and a

IQueryable<Customer> query = ..//fetch from dbContext;

I want to dynamically create an expression that selects these properties from the query.

the end result would have to execute as follows:

Expression<IQueryable<Customer>,IQueryable<dynamic>> query = query.Select(x=>new{
  x=>x.Name,
  x=>x.MarketSegment.Name
});

I figured out that Expression.New could be an option in this question, but I'm unable to figure out how to pass expressions to it.