Search code examples
c#listlambdatreeexpression

Expression Tree with List parameters


I want to create a c# Expression Tree for the following case:

EntityA.Where(x => list.Any(y => y == x.SomeProperty))

I made a few attempts and found a few similar examples online, but nothing exactly like the above.

Any suggestions, references, solutions would be appreciated.


Solution

  • using System.Linq.Expressions;
    using System.Reflection;
    
    // example data
    IQueryable<Foo> source = Enumerable.Range(0, 10)
        .Select(x => new Foo { SomeProperty = x })
        .ToList().AsQueryable();
    List<int> list = [ 1, 4 ];
    
    // expression tree construction
    var any = typeof(Enumerable)
        .GetMethods(BindingFlags.Public | BindingFlags.Static)
        .Single(m => m.IsGenericMethodDefinition
                  && m.Name == "Any"
                  && m.GetParameters().Length == 2
               ).MakeGenericMethod(typeof(int));
    var x = Expression.Parameter(typeof(Foo), "x"); // the type from "source"
    var y = Expression.Parameter(typeof(int), "y"); // the type from "list"
    var inner = Expression.Lambda<Func<int, bool>>(
        Expression.Equal(y, Expression.Property(x, "SomeProperty")), y);
    Console.WriteLine(inner);
    var outer = Expression.Lambda<Func<Foo, bool>>(
        Expression.Call(null, any, Expression.Constant(list), inner), x);
    Console.WriteLine(outer);
    var query = source.Where(outer);
    
    // show it working
    foreach (var item in query)
    {
        Console.WriteLine(item.SomeProperty);
    }
    class Foo
    {
        public int SomeProperty { get; set; }
    }