1

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 ?

2
  • Please could you show some code Commented Mar 9, 2013 at 12:31
  • Am in initial stage of implementing. Just want to confirm with you guys on what is the best approach ? Commented Mar 9, 2013 at 12:50

1 Answer 1

3

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.

Sign up to request clarification or add additional context in comments.

4 Comments

Thanks. I got the idea behind Expression trees. But how do i do at run time.In My case how i know if user is searching for 1 attribute value or 5 attribute. only i know after he clicks the button right ?
Also are customizable in my question like Height > 170 all three parameters will be entered by user at run time
This require a bit more intelligence in the system. What you are saying would require input inference ex 1 or many parameters would translate to either equal or in operation. But the permutation of these cases could be prohibitive in some other cases.
You can definitely provide some customization, but it would be good if there are boundaries. Otherwise you would see the user asking for SQL like features. Not that it is impossible, it may not be worth the effort, there are better tools for querying/reporting.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.