c# - Lambda Expression to be used in Select() query -
i trying build lambda expression, containing 2 assignments (as shown further down), can pass queryable.select() method.
i trying pass string variable method , use variable build lambda expression can use in linq select query.
my reasoning behind have sql server datasource many column names, creating charting application allow user select, typing in column name, actual column of data want view in y-axis of chart, x-axis being datetime. therefore, can choose data chart against datetime value (it’s data warehouse type app).
i have, example, class store retrieved data in, , hence use chart source of:
public class analysischartsource { public datetime invoicedate { get; set; } public decimal yvalue { get; set; } }
i have (purely experimentaly) built expression tree clause using string value , works fine:
public void getdata(string yaxis) { using (dataclasses1datacontext db = new dataclasses1datacontext()) { var data = this.functionone().asqueryable<analysischartsource>(); //just temp data in.... parameterexpression pe = expression.parameter(typeof(analysischartsource), "p"); expression left = expression.makememberaccess(pe, typeof(analysischartsource).getproperty(yaxis)); expression right = expression.constant((decimal)16); expression e2 = expression.lessthan(left, right); expression expnew = expression.new(typeof(analysischartsource)); lambdaexpression le = expression.lambda(left, pe); methodcallexpression wherecall = expression.call( typeof(queryable), "where", new type[] { data.elementtype }, data.expression, expression.lambda<func<analysischartsource, bool>>(e2, new parameterexpression[] { pe })); } }
however……i have tried similar approach select statement, can’t work need select() populate both x , y values of analysischartsource class, this:
.select(c => new analysischartsource { invoicedate = c.invoicedate, yvalue = c.yvalue}).asenumerable();
how on earth can build such expression tree….or….possibly more point…..is there easier way have missed entirely?
i find best way work out how build expression trees see c# compiler does. here's complete program:
using system; using system.linq.expressions; public class foo { public int x { get; set; } public int y { get; set; } } class test { static void main() { expression<func<int, foo>> builder = z => new foo { x = z, y = z }; } }
compile that, open results in reflector , set optimisation .net 2.0. end generated code main method:
parameterexpression expression2; expression<func<int, foo>> expression = expression.lambda<func<int, foo>>( expression.memberinit( expression.new((constructorinfo) methodof(foo..ctor), new expression[0]), new memberbinding[] { expression.bind((methodinfo) methodof(foo.set_x), expression2 = expression.parameter(typeof(int), "z")), expression.bind((methodinfo) methodof(foo.set_y), expression2) } ), new parameterexpression[] { expression2 });
basically, think expression.memberinit
you're after.
Comments
Post a Comment