Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# Dynamic Linq Variable Where clause

Tags:

c#

linq

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

like image 319
gunnerz Avatar asked Jun 25 '12 12:06

gunnerz


2 Answers

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.

like image 68
Wiktor Zychla Avatar answered Oct 04 '22 01:10

Wiktor Zychla


Try this;

Dynamic linq query with multiple/unknown criteria

I had a similiar problem and that was a solution that I used (and is still in use)

like image 45
ChrisBint Avatar answered Oct 04 '22 02:10

ChrisBint