Search code examples
c#.netexpressionbinary-search-treeexpression-trees

LINQ Expression tree with Substring


I want to create SQL LINQ expression like:

.Where(product => product.name.Substring(3,5).Contains("ma")

Can someone help me to create that expression?

Expression.PropertyOrField(body, "name.Substring(3,5)");

I tried, but I am getting an error

Substring(3,5) is not a member of type 'System.String'


Solution

  • Assume we have a class Product:

    public class Product
    {
        public string name;
    }
    

    Then you can create your Expression as:

    Expression<Func<Product, bool>> expression = product => product.name.Substring(3, 5).Contains("ma");
    Console.WriteLine(expression); // product => product.name.Substring(3, 5).Contains("ma")
    

    If you need to create your expression manually consider this:

    var parameter = Expression.Parameter(typeof(Product), "product");
    var expression = Expression.Lambda<Func<Product, bool>>(
        Expression.Call(
            Expression.Call(
                Expression.PropertyOrField(parameter, "name"),
                typeof(string).GetMethod("Substring", new[] { typeof(int), typeof(int) }),
                Expression.Constant(3, typeof(int)),
                Expression.Constant(5, typeof(int))),
            typeof(string).GetMethod("Contains", new[] { typeof(string) }),
            Expression.Constant("ma", typeof(string))),
        parameter);
    Console.WriteLine(expression); // product => product.name.Substring(3, 5).Contains("ma")
    

    Hope was helpful for you.