JaimeCamargo
JaimeCamargo

Reputation: 363

Get resulting LINQ expression from LINQ Dynamic WHERE

I have the next code in LINQ Dynamic:

var list = server1Products.Where("Field1 = @0 AND Field2 >= @2", arg1, arg2).ToList();

I need to get the resulting LINQ Expression after using the LINQ Dynamic WHERE, so use it in another list.

How to get this resulting LINQ Expression?

.Where("Field1 = @0 AND Field2 >= @2", arg1, arg2)

Example:

// get the LINQ expression from WHERE
var conditions = GetExpresionFromWhere(list); // HOW TO DO?
//
// apply the same filter expression on another list
var result2 = list2.Where(conditions);

Thanks a lot!

Upvotes: 0

Views: 435

Answers (3)

haim770
haim770

Reputation: 49123

In essence, what DynamicLinq does for you here is to parse the string you're passing in (along with the arguments) into an Expression<Func<T, bool>>.

So, in order to have the desired Expression<Func<T, bool>> stored in a variable, you can do this:

var conditions = DynamicExpression.ParseLambda<ENTITY, bool>("Field1 = @0 AND Field2 >= @1", arg1, arg2);

(Where ENTITY is your entity type)

Then use it:

var result2 = list2.Where(conditions);

Also, in case list2 is no longer an IQueryable<ENTITY> but an IEnumerable<ENTITY>, you'll have to compile the Expression into Func<ENTITY, bool> as follows:

var result2 = list2.Where(conditions.Compile());

See Source

Upvotes: 2

Rion Williams
Rion Williams

Reputation: 76607

While it's unlikely that you could resolve the expression that was used on a list after it has already been executed, you could consider storing the expression and using it in multiple locations :

Expression<Func<ServerProductClass, bool>> conditions = BuildWhereExpression();

Where your BuildWhereExpression() method looked something like the following and would generate the necessary expression :

public Expression<Func<ServerProductClass, bool>> BuildExpression(string predicate, object[] terms)
{
     return DynamicExpression.ParseLambda<ServerProductClass, bool>(predicate, terms);
}

So your entire code might look something like this :

// Build your condition
var condition = BuildExpression("Field1 = @0 AND Field2 >= @2", new object[]{arg1, arg2 });

// Filter your initial list
list = list.Where(condition).ToList();

// Use it again later
var list2 = someOtherList.Where(condition).ToList();

Upvotes: 1

Sebastian Siemens
Sebastian Siemens

Reputation: 2421

// get the LINQ expression from WHERE
// Entity => your type of items in server1Products
Expression<Func<Entity, int>> conditions = x => x.Field1 == arg1 && x.Field2 = arg2;


// apply the same filter expression on another list
var result2 = list2.Where(conditions);

Upvotes: 1

Related Questions