c# - Dynamic Lambda with all properties of a property of an object -
i had asked question on how dynamically compile linq query properties of object , houlgap had been kind enough give me following code
private static func<myentity, bool> generatelambda(myentity _myentity, propertyinfo propertyinfo) { var instance = expression.parameter(propertyinfo.declaringtype, "i"); var property = expression.property(instance, propertyinfo); var propertyvalue = expression.constant(propertyinfo.getvalue(_myentity, null)); var equalitycheck = expression.equal(property, propertyvalue); return expression.lambda<func<myentity, bool>>(equalitycheck, instance).compile(); }
this works great if property queried directly member of object me there intermediate property in between. e.g. func delegate type e.g. func<abcmyentity,bool>
while myentity member of object (abcmyentity.myentity). propertyinfo object passed member of myentity.
i know sounds terribly confusing not able better explain it. (maybe because not native speaker). please ask me if not clear in question.
it continued constructing dynamic linq queries properties of object
if need access chain of properties (e.g. v.myentity.otherproperty
) can call expression.property
multiple times:
var prop1 = // first property var prop2 = // second property // variable has type of declarating type of 1st property var instance = expression.parameter(prop1.declaringtype, "i"); // first property on 'instance' var expr1 = expression.property(instance, prop1); // second property on previous expression var expr2 = expression.property(expr, prop2); // rest of code stays same (only use 'expr2') var propertyvalue = expression.constant(propertyinfo.getvalue(_myentity, null)); var equalitycheck = expression.equal(expr2, propertyvalue); return expression.lambda<func<myentity, bool>> (equalitycheck, instance).compile();
if need access more 2 properties, can turn part calls expression.property
loop - iterate on list of desired properties , add property access expression using expression.property
.
Comments
Post a Comment