I am looking at implementing a generic filtering and sorting mechanism for my application services.
Having done some research it appears that LINQKit is ideal for this using the predicate builder. I have also found some articles that go into some nice detail in terms of implementation:
The one thing I have not seen anyone do however is conditional logic of the WHERE clause. Every example I have seen seems to only AND the where conditions.
I am looking for something where I can build up more complex expressions such as:
WHERE ((Field1 = 1 OR Field1 = 2) AND Field2 = 3) OR Field4 = 'A'
Has anyone seen an implementation that adds conditional logic to a generic implementation of filters?
Expression Trees could be your answer. Here are also OR conditions and many more possible. Here my example:
IQueryable<ENTITY> query = context.ENTITY;
Expression whereExpression = null;
ParameterExpression pe = Expression.Parameter(typeof(ENTITY), "name");
Expression left1 = MemberExpression.Property(pe, "Field1");
Expression right1 = Expression.Constant(1, typeof(int));
whereExpression = Expression.And(whereExpression, Expression.Equal(left1, right1));
Expression left2 = MemberExpression.Property(pe, "Field1");
Expression right2 = Expression.Constant(2, typeof(int));
whereExpression = Expression.Or(whereExpression, Expression.Equal(left2, right2));
Expression left3 = MemberExpression.Property(pe, "Field2");
Expression right3 = Expression.Constant(3, typeof(int));
whereExpression = Expression.And(whereExpression, Expression.Equal(left3, right3));
Expression left4 = MemberExpression.Property(pe, "Field4");
Expression right4 = Expression.Constant("A", typeof(string));
whereExpression = Expression.Or(whereExpression, Expression.Equal(left4, right4));
Expression<Func<ENTITY, bool>> whereCondition = Expression.Lambda<Func<ENTITY, bool>>(whereExpression, new ParameterExpression[] { pe });
query = query.Where(whereCondition);
return query.ToList();
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.