Wapac Wapac - 1 year ago 87
C# Question

Making generic expression generating method in C#

I am constructing an IQueryable query using several methods. The methods are somehow complex, 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 what I would rather have is 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 having two same methods with the only difference being in what property of an object is being used there.

Is it possible to do this in some elegant way?

Answer Source

You can pass in a selector Func that returns a string property:

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


CreateExpression<MyType>(x => x.PropertyA, "thevalue");
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download