Search code examples
c#linqdynamiclambdaexpression-trees

Dynamic lambda expression for ICollection column


I am trying to generate dynamic lambda expression for filtering ICollection field. In Linq it would look like this:

.Where(x => x.Remarks.Any(s => s.Remark.Description.Contains("filter")))

I have done the last part: s => (s.Remark.Description.Contains("filter"))

MethodInfo containsMethod = typeof(string).GetMethod("Contains", new[] { typeof(string) });
var parameterExpression = Expression.Parameter(Type.GetType("RemarksModel"), "s");
var constant = Expression.Constant("filter");
var property = Expression.Property(parameterExpression, "Remark");
property = Expression.Property(property, "Description");

var expression = Expression.Call(property, containsMethod, constant);

var lambda = Expression.Lambda<Func<remarkModel, bool>>(expression, parameterExpression);

Now I am having truble with adding first part with .Any() to this.

Model with collection looks like this:

public class ReadsModel { 
    public ICollection< RemarksModel > Remarks { get; set; }
}

public class RemarksModel {
    [ForeignKey("RemarkId")]
    public virtual RemarkModel Remark { get; set; }
    [ForeignKey("ReadsId")]}
    public virtual ReadsModel MeterRead { get; set; }
}

public class RemarkModel {
    public string Description { get; set; }
}

Solution

  • If we remove the C# compiler extension method sugar and type inference from

    x => x.Remarks.Any(lambda)
    

    the actual expression would look like

    (ReadsModel x) => Enumerable.Any<RemarksModel>(x.Remarks, lambda)    
    

    Hence the code for building it using the Expression class could be like this

    var parameter = Expression.Parameter(typeof(ReadsModel), "x");
    var body = Expression.Call(
        typeof(Enumerable), // class containing the static method
        nameof(Enumerable.Any), // method name
        new Type[] { typeof(RemarksModel) }, // generic type arguments
        Expression.Property(parameter, "Remarks"), lambda // method arguments
    );
    var predicate = Expression.Lambda<Func<ReadsModel, bool>>(body, parameter);