简体   繁体   中英

Construct where clause at runtime

I want to use a totally dynamic where clause with linq where column , operator, as well as value to match all are decided at run-time. Please suggest how can i use it , if possible. I want to do something like :

ObjDataTable.AsEnumerable().Where(whereClause);

Here are two possible options (there may be more):

LINQ Dynamic Query Library

Dynamic Linq allows you to generate LINQ queries dynamically at runtime.

You can use the DynamicQuery library against any LINQ data provider (including LINQ to SQL, LINQ to Objects, LINQ to XML, LINQ to Entities, LINQ to SharePoint, LINQ to TerraServer, etc). Instead of using language operators or type-safe lambda extension methods to construct your LINQ queries, the dynamic query library provides you with string based extension methods that you can pass any string expression into.

using System.Linq.Dynamic; //Make sure you reference Dynamic.dll

string whereClause = "CategoryID=2 AND UnitPrice>2";
ObjDataTable.AsEnumerable().AsQueryable().Where(whereClause);

NOTE: When you download the Dynamic LINQ library, the .dll you'll need to reference is buried under the following path: .\\LinqSamples\\DynamicQuery\\DynamicQuery\\bin\\Debug

LinqKit.PredicateBuilder

PredicateBuilder is a class in the LinqKit library. It's typesafe, and allows you to dynamically create expressions. Perhaps a higher learning curve than Dynamic Linq , but it's worth checking out.

Of all the things that will drive you to manually constructing expression trees, the need for dynamic predicates is the most common in a typical business application. Fortunately, it's possible to write a set of simple and reusable extension methods that radically simplify this task. This is the role of our PredicateBuilder class.

You can add filtering at runtime with methods syntax:

var query = ObjDataTable.AsEnumerable();
if (condition)
    query = query.Where(whereClause);

You will have nice strongly typed whereClause in this case (instead of strings).

Have you checked out the Dynamic Expression API ( available on NuGet ) for this. It seems pretty straight forward and easy to use?

If that doesn't work, you'd have to create Expression 's at runtime, which can be a pain in my experience.

使用动态LINQ ,因此您可以将whereClause作为字符串传递

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.

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