简体   繁体   English

如何使用C#和Linq实现动态搜索功能?

[英]How to implement dynamic search functionality using C# and Linq?

I am trying to implement a dynamic search functionality in C#. 我正在尝试在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. 与属性匹配的列名称可能来自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 我对Linq相当陌生,我正在尝试了解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 ? 实施此的最佳方法是什么?

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 . 参考表达式树ExpressionType

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM