Convert Contains To Expression Tree

c# c#-6.0 expression-trees lambda linq

Question

Related To: Create a Lambda Expression With 3 conditions

Please consider this Code:

from a in myTbl
where a.Address.Contains(strToCheck)
select a

How I can convert this to Expression Tree and write above code with Expressions? Main Problem is converting a.Address.Contains(strToCheck) to Expression Tree.

Edit 1) Address is a string field and strToCheck is a string

Thanks

1
0
9/28/2017 6:08:17 AM

Accepted Answer

a.Address.Contains(strToCheck) represents a call to string.Contains instance method on a.Address instance with strToCheck argument.

The simplest way to build the corresponding expression is to use the following Expression.Call overload:

public static MethodCallExpression Call(
    Expression instance,
    string methodName,
    Type[] typeArguments,
    params Expression[] arguments
)

like this (using the terms from the linked question):

var body = Expression.Call(
    Expression.PropertyOrField(param, "Address"), // instance
    "Contains", // method
    Type.EmptyTypes, // no generic type arguments
    Expression.Constant(strToCheck) // argument
);
3
9/25/2017 12:57:08 PM

Popular Answer

You did not specify the type of myTbl,
So I have created a simple solution using just a list of objects.

using System;
using System.Linq;
using System.Linq.Expressions;
using System.Collections.Generic;

namespace Test
{
    class Program
    {
        static void Main(string[] args) {
            var adresses = FilterByAddress("Address", new List<Person> { new Person { Address = "Address1" }, new Person { Address = "AAAAAA" } });
        }

        public static IEnumerable<Person> FilterByAddress(string strToCheck, List<Person> list) {
            var listParam = Expression.Parameter(typeof(IEnumerable<Person>), "list");
            Expression<Func<Person, bool>> contains = a => a.Address.Contains(strToCheck);
            var select = typeof(Enumerable).GetMethods().Single(m => m.Name.Equals("Where") && m.GetParameters()[1].ParameterType.GetGenericArguments().Length == 2);
            var genericMethod = select.MakeGenericMethod(new[] { typeof(Person) });
            var call = Expression.Call(null, genericMethod, new Expression[] { listParam, contains });
            var lambda = Expression.Lambda<Func<IEnumerable<Person>, IEnumerable<Person>>>(call, new[] { listParam });

            return lambda.Compile().Invoke(list);
        }
    }

    public class Person
    {
        public string Address { get; set; }
    }
}

If you want to use a filter by predicate you can pass an Expresssion<Func<Person, bool>> as parameter (one line)

    static void Main(string[] args) {
        var strToCheck = "Address";
        var list = new List<Person> { new Person { Address = "Address1" }, new Person { Address = "AAAAAA" } };
        var adresses = FilterByAddress(list, p => p.Address.Contains(strToCheck));
    }

    public static IEnumerable<Person> FilterByAddress(List<Person> list, Expression<Func<Person, bool>> predicateEx) {
        var listParam = Expression.Parameter(typeof(IEnumerable<Person>), "list");
        var select = typeof(Enumerable).GetMethods().Single(m => m.Name.Equals("Where") && m.GetParameters()[1].ParameterType.GetGenericArguments().Length == 2);
        var genericMethod = select.MakeGenericMethod(new[] { typeof(Person) });
        var call = Expression.Call(null, genericMethod, new Expression[] { listParam, predicateEx });
        var lambda = Expression.Lambda<Func<IEnumerable<Person>, IEnumerable<Person>>>(call, new[] { listParam });

        return lambda.Compile().Invoke(list);
    }

In case you have a very compilicated predicate which spans to multiple lines (an expression tree can be evaluated from a one line lambda) you can use a trick to construct an expression tree out of the predicate Func like this:

    static void Main(string[] args) {
        var strToCheck = "Address";
        Func<Person, bool> predicate = p => {
            return p.Address.Contains(strToCheck);
        };

        var list = new List<Person> { new Person { Address = "Address1" }, new Person { Address = "AAAAAA" } };
        var adresses = FilterByAddress(list, predicate);
    }

    public static IEnumerable<Person> FilterByAddress(List<Person> list, Func<Person, bool> predicate) {
        var listParam = Expression.Parameter(typeof(IEnumerable<Person>), "list");
        Expression<Func<Person, bool>> predicateEx = p => predicate(p);
        var select = typeof(Enumerable).GetMethods().Single(m => m.Name.Equals("Where") && m.GetParameters()[1].ParameterType.GetGenericArguments().Length == 2);
        var genericMethod = select.MakeGenericMethod(new[] { typeof(Person) });
        var call = Expression.Call(null, genericMethod, new Expression[] { listParam, predicateEx });
        var lambda = Expression.Lambda<Func<IEnumerable<Person>, IEnumerable<Person>>>(call, new[] { listParam });

        return lambda.Compile().Invoke(list);
    }

Using the generic approach to filter a list by predicate

    static void Main(string[] args) {
        var strToCheck = "Address";
        Func<Person, bool> predicate = p => {
            return p.Address.Contains(strToCheck);
        };

        var list = new List<Person> { new Person { Address = "Address1" }, new Person { Address = "AAAAAA" } };
        var adresses = FilterBy<Person>(list, predicate);
    }

    public static IEnumerable<T> FilterBy<T>(List<T> list, Func<T, bool> predicate) {
        var listParam = Expression.Parameter(typeof(IEnumerable<T>), "list");
        Expression<Func<T, bool>> predicateEx = p => predicate(p);
        var select = typeof(Enumerable).GetMethods().Single(m => m.Name.Equals("Where") && m.GetParameters()[1].ParameterType.GetGenericArguments().Length == 2);
        var genericMethod = select.MakeGenericMethod(new[] { typeof(T) });
        var call = Expression.Call(null, genericMethod, new Expression[] { listParam, predicateEx });
        var lambda = Expression.Lambda<Func<IEnumerable<T>, IEnumerable<T>>>(call, new[] { listParam });

        return lambda.Compile().Invoke(list);
    }
}


Related Questions





Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow