To set a comparison operator in linq query dynamically, i do the following:
parameter = Expression.Parameter(typeof(SomeType));
var predicate = Expression.Lambda<Func<SomeType, bool>>(
Combine(
"=",
Expression.Property(parameter, "ID"),
Expression.Constant(150497)
), parameter);
BinaryExpression Combine(string op, Expression left, Expression right)
{
switch (op)
{
case "=":
return Expression.Equal(left, right);
case "<":
return Expression.LessThan(left, right);
case ">":
return Expression.GreaterThan(left, right);
}
return null;
}
That works. But I'd rather pass a lambda expression as parameter "left" instead. Is that possible? Something like:
var predicate = Expression.Lambda<Func<SomeType, bool>>(Combine(
"=",
c => c.ID,
Expression.Constant(150497)
), parameter);
What about this? Unfortunately, I cannot test it now, so give me know if it doesn't work
Basically you want to access a class' fields without using strings, and that is doable iff your fields are public.
Here you can see a good example of how that's done.
As for your specific usage of it, it'd be something along the lines of:
Disclaimer: Didn't test it, but logic is there.
As mentionned, you wouldn't be able to access
SomeType.aString
because it isprivate
. Also I puttypeof(int)
but if you want even that to be dynamic you could have another method (i.e.GetMemberType
) to get the field's type.