Reputation: 3803
I am trying to implement a dynamic search functionality in C#. My search will be like
Attribute operand Value === > Height > 170
Like the above search list goes on dynamically as user can add as much as he wants to filter that data. And Attribute matches my Column name might be from different tables in SQL DB.
What is the best way to implement these kind of searches? I am pretty new to Linq and I am trying to understand http://www.albahari.com/nutshell/predicatebuilder.aspx
How can I dynamically build query or What will be the best way for these sort of searches which is easy to maintain?
Example:
Attribute operand Value === > Height = 170
Attribute operand Value === > Altitude > 40000
Attribute operand Value === > temperature < 105
Everything is customizable to user and build at run time .
What is the best way to implement this ?
Upvotes: 1
Views: 2773
Reputation: 9049
Check this answer in this question for an example on how to build an expression dynamically.
In your case I think something like this should help (wrote this off top of my head, pls excuse syntax errors).
PropertyInfo propInfo = typeof(T).GetProperty(Attribute);
ParameterExpression pe = Expression.Parameter(typeof(Attribute), Attribute);
Expression right = Expression.Parameter(typeof(int), Value);
Expression predicateBody = Expression.GreaterThan(left, right);
Expression<Func<int, bool>> lambda1 =
Expression.Lambda<Func<int, bool>>(
predicateBody,
new ParameterExpression[] { numParam });
Reference - Expression Trees and ExpressionType.
Upvotes: 3