Wednesday, September 5, 2018

Prepare dynamic expression (predicate) to IQueryable ( c# / .NET / Linq)


In the following example, the returning expression is for 'equal' operator. ( you can find other operations like 'GreaterThan','NotEqual' etc). Let 'TEntity' be the entity for which you want to prepare the predicate. Then, the parameter would be

 ParameterExpression parameter = Expression.Parameter(typeof(TEntity));

Lets say for column 'id' you want to create an expression to filter records with value equal to '5'. Then you can prepare the expression as

object valueObject = new object();
valueObject = (int)5;

var _expression = Expression.Equal(Expression.Property(parameter, "id"), Expression.Constant(valueObject, typeof(int)));
var  _lambdaExpression = Expression.Lambda<Func<TEntity, bool>>(_expression, parameter);

This _lambdaExpression can now be used as predicate for your queryable of TEntity as

var filteredList = MyQueryable.Where(_lambdaExpression).ToList();

Additionally, if you want to have AND/OR operations within the expression, you can do it as following.

let _expression1 and _expression2 be two expressions. For AND operation :

var _expression3 = Expression.And(_expression1, _expression2);

This _expression3 can now be used to create the lambda expression.

Note : namespace System.Linq.Expressions.Expression