Search code examples
c#linq.net-coreexpression-trees

C# Expression trees - combine multiple method calls


I'm using .Net Core and expression trees.

I have a Product class, where LstProp property contains list of values separated by ';', like "val1;val2;val3;":

public class Product
{
  // actually contains list of values separated by ';'
  public string LstProp{get; set;}
}

And I want to filter Products by this property and contains any condition using expression trees. I've try this, but it doesn't work.

 var value="val1;val2"
 var productItem = Expression.Parameter(typeof(Product), "product");
 var prop = Expression.Property(productItem, "LstProp");

 MethodInfo method = typeof(string).GetMethod("Contains", new[] { typeof(string) });
 var values = value.ToString().Split(';');
 Expression predicate = null;
 foreach (var val in values)
 {
    var listPropExpression = Expression.Constant(val);
    var containsExpresion=Expression.Call(listPropExpression, method, property);
    predicate = predicate != null ? Expression.Or(predicate, containsExpresion) : containsExpresion;
 }

So I'm trying to combine call of Contains function for each value in the list, but getting error about "No conversion between BinaryExpression and MethodCallExpression".

How could I combine multiple method calls with expression trees?


Solution

  • I have found solution. I got two problems:

    1. Incorrect order of parameters. Should be Expression.Call(property, method, listPropExpression); instead Expression.Call(listPropExpression, method, property);

    2. Main problem was solved with simple cast:

      predicate = predicate != null ? (Expression) Expression.Or(predicate, containsExpresion) : containsExpresion;

    As a Result I get expression like product=>product.LstProp.Contains("val1") Or product.LstProp.Contains("val2")