I'm attempting to modify an expression tree that dynamically builds a Contains expression that ultimately results in SQL like
P IN (123, 124, 125, 200, 201)
to instead check perform range checks, which ultimately results in SQL like
(P >= 123 AND P <= 125) OR (P >= 200 AND P <= 201)
I'm basing my solution on this post.
static public Expression<Func<TElement, bool>>
BuildContainsExpression<TElement, TValue>(
Expression<Func<TElement, TValue>> valueSelector, IEnumerable<TValue> values)
{
// Removed for post: Input checks and edge cases
var equals =
values.Select(value =>
(Expression)Expression.Equal(valueSelector.Body,
Expression.Constant(value, typeof(TValue))));
var body = equals.Aggregate<Expression>((accumulate, equal) =>
Expression.Or(accumulate, equal));
return Expression.Lambda<Func<TElement, bool>>(body, p);
}
I'm able to get the range checking to work if I provide the value for comparison:
long testValue = 5;
List<KeyValuePair<int, int>> ranges = new List<KeyValuePair<int, int>>()
{
new KeyValuePair<long, long>(3, 6),
new KeyValuePair<long, long>(10, 12),
new KeyValuePair<long, long>(20, 20),
};
List<BinaryExpression> rangeExpressions = new List<BinaryExpression>();
foreach (var pair in ranges)
{
var greaterThanOrEqual =
Expression.GreaterThanOrEqual(Expression.Constant(testValue),
Expression.Constant(pair.Key));
var lessThanOrEqual =
Expression.LessThanOrEqual(Expression.Constant(testValue),
Expression.Constant(pair.Value));
var inRange = Expression.AndAlso(greaterThanOrEqual, lessThanOrEqual);
rangeExpressions.Add(inRange);
}
var final =
rangeExpressions.Aggregate<Expression>((a, b) => Expression.Or(a, b));
var result = Expression.Lambda<Func<bool>>(final).Compile()();
However, I cannot sort out how to get the value for comparison from the passed-in expression when I drop that code into the method to be used with Linq. The signature of that method is:
Expression<Func<TElement, bool>>
BuildRangeExpression<TElement>(
Expression<Func<TElement, long>> valueSelector,
IEnumerable<long> values)
and it is used like:
Expression<MyType, bool> match =
BuildRangeExpression<MyType, long>(my => my.ProductCode, productCodes);
var result = db.MyTypes.Where(match);
QUESTION
How can I evaluate
Expression<Func<TElement, long>> valueSelector
so that I can use the value passed into BuildRangeExpression
instead of my currently hard-coded value
long testValue = 5;