rooma
rooma

Reputation: 21

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);

Upvotes: 2

Views: 604

Answers (4)

Aaron Blenkush
Aaron Blenkush

Reputation: 3059

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.

Upvotes: 4

cuongle
cuongle

Reputation: 75306

Make use of dynamic LINQ, so you can pass whereClause as string

Upvotes: 1

p.s.w.g
p.s.w.g

Reputation: 149010

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.

Upvotes: 1

Sergey Berezovskiy
Sergey Berezovskiy

Reputation: 236208

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).

Upvotes: 1

Related Questions