7

I am following Scott Gu's article to create a dynamic LINQ http://weblogs.asp.net/scottgu/archive/2008/01/07/dynamic-linq-part-1-using-the-linq-dynamic-query-library.aspx

He has given an example:

Expression<Func<Customer, bool>> e1 = 
    DynamicExpression.ParseLambda<Customer, bool>("City = \"London\"");  
Expression<Func<Customer, bool>> e2 =
    DynamicExpression.ParseLambda<Customer, bool>("Orders.Count >= 10");  
IQueryable<Customer> query =
    db.Customers.Where("@0(it) and @1(it)", e1, e2);  

This works fine in my case. However I have unknown number of where clauses, which is decided at runtime.

Can anyone please tell me how to create a generic Where clause, such as

Where("@0(it) and @1(it) and... @n(it)", e1, e2, ... en);

Thanks

1
  • How about trying with something like db.Customers.Where( c => c.Order.Count > someVariable1 && c.Order.Count < someVariable2 ); Commented Jun 25, 2012 at 13:20

2 Answers 2

19

You can attach additional operators on the query object:

 query = db.Customers.Where( ... );
 query = query.Where( ... );
 query = query.Where( ... );

This way you can attach clauses dynamically and you are independent on their count.

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

2 Comments

Thanks Thats what I am doing now
how to do IN clause in where?
0

I have created a nuget package called DynamicFilter.Sql to achieve exactly this. For my requirement, I wanted to generate LINQ expression trees from sql syntax.

Here is how you would use it in your case.

var filter = FilterExpression.Compile<Customer>("City = 'London' and OrderCount >= 10");

//Filter a collection
var filteredCustomers = customers.Where(filter);

The package can generate code for complex logical/boolean operations and support sql style filtering including like, not like, in, not in, is null, is not null etc.

The package is open source and available on github, in case you would like to check the internals.

Comments

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.