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 ?

user2067567
  • 3,695
  • 15
  • 49
  • 77

1 Answers1

2

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.

Community
  • 1
  • 1
Srikanth Venugopalan
  • 9,011
  • 3
  • 36
  • 76
  • 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 ? – user2067567 Mar 11 '13 at 07:14
  • Also are customizable in my question like Height > 170 all three parameters will be entered by user at run time – user2067567 Mar 11 '13 at 07:15
  • 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. – Srikanth Venugopalan Mar 11 '13 at 07:47
  • 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. – Srikanth Venugopalan Mar 11 '13 at 07:48