Creating a universal method for generating expressions in C #

I am creating an IQueryable query using several methods. The methods are somehow complicated, but the problem I want to solve can be extracted and simplified as follows. I have two methods

private Expression<Func<T, bool>> CreateExpressionA(string ValueA)
{
  return a => a.PropertyA.ToLower() == ValueA;
}

private Expression<Func<T, bool>> CreateExpressionB(string ValueB)
{
  return a => a.PropertyB.ToLower() == ValueB;
}

and I would prefer this:

private Expression<Func<T, bool>> CreateExpression(??? Selector, string Value)
{
  return a => a.Selector.ToLower() == Value;
}

or a similar approach that would allow me to avoid using two identical methods, with the only difference in which the property of the object is used.

Can this be done in some elegant way?

+4
source share
3 answers

You can pass a selector Functhat returns a property string:

private Expression<Func<T, bool>> CreateExpression<T>(Func<T, string> selector, string value)
{
    return a => selector(a).ToLower() == value;
}

Using:

CreateExpression<MyType>(x => x.PropertyA, "thevalue");
+4
source

, PropertyInfo, . .

private Expression<Func<T, bool>> CreateExpression(PropertyInfo iInfo, string Value)
{
    return a => (iInfo.GetPropertyValue(a) as string).ToLower() == ValueB;
}

, , string, .

+1

What you can do is create an expression from scratch:

private Expression<Func<T, bool>> CreateExpression(string propertyName, string value) {
    ParameterExpression param = Expression.Parameter(typeof(T));
    MemberExpression property = Expression.Property(param, propertyName);
    var valExpr = Expression.Constant(value);
    var body = Expression.Equal(property, valExpr);
    return Expression.Lambda<Func<T, bool>>(body, param);
}

Call using:

var expression = CreateExpression<TypeOfA>("PropertyA", "ValueForPropertyA");

It's a bit of a head, but I think this should at least start. Let me know if you need any help.

0
source

Source: https://habr.com/ru/post/1660694/


All Articles