c# - Assign variable to Expression<Func<TSource, bool>> -


using net 4.5.1

have following class respondent:

namespace whatever {   public class respondent {     public int x { get; set; }     public int y { get; set; }      public static expression<func<respondent, bool>> comparexy(int value) {       return x => ((x.x * 100) + x.y) > value;     }   } } 

lets want pass body of lamdba around. getting by:

... function ... type membertype = typeof(<this class>).assembly.gettype("whatever.respondent");  object[] parameters = new object[] { <populate integer value> };  var expr = membertype   .getmethod(memberfunctionname, bindingflags.public | bindingflags.static)   .invoke(null, parameters) lambdaexpression;  return expr.body 

problem variable x (i.e. respondent) not defined. example, functional expression comparexy might included in larger expression tree derives series of predicates (i.e. standing comparisons, literals, functions, etc):

...function returning expression<func<respondent, bool>>... expr = predicates.aggregate(   (prev, next) => new , { operands = new expr[] { prev, next}  } );  expression composition = together.getexpression(context);  <-- here resolving comparexy return expression.lambda(composition, new parameterexpression[] { context }); 

basically, body of lambda returned comparexy has have variable/parameter x set respondent type.

edit, getting following error:

 {"variable 'x' of type 'charting.models.respondent' referenced scope '',   not defined"} 

question how define variable x body of lambda?

i'm not entirely sure there's question in there, think answered it:

the body of lambdaexpression doesn't include parameters. in expr.parameters. if need re-use body of lambda, you'll need recreate it.

alternatively, can pass lambda in entirety, call use invokeexpression invoke lambda.

edit: answer question, must pass parameters along body of expression. parameter used must reference equivalent what's in expr.parameters. can't substitute newly created parameterexpression.


Comments

Popular posts from this blog

How do you convert a timestamp into a datetime in python with the correct timezone? -

how to display 2 form fields on same line with bootstrap -

c# - how to use buttonedit in devexpress gridcontrol -