C# Expression String.IndexOf case insensitive with the property selector

356 views Asked by At

I have the following class and extension method to invoke String.Contains method. How can I change it to be case insensitive ? Something like in Expression tree for String.IndexOf method but I don't have an ideas so far how to adjust that code into my code. Any help ?

public class testItem
{
    public string SomeProperty { get; set; }
}

public static IQueryable<testItem> PropertyContainsNEW<testItem>(this IQueryable<testItem> source,
                                                                Expression<Func<testItem, string>> selector,
                                                                string value)
{
    ParameterExpression parameter = Expression.Parameter(typeof(testItem), "x");
    Expression property = Expression.Property(parameter, ((MemberExpression)selector.Body).Member.Name);
    var search = Expression.Constant(value, typeof(string));

    MethodInfo method = typeof(string).GetMethod("Contains", new[] { typeof(string) });
    var containsMethodExp = Expression.Call(property, method, search);

    var predicate = Expression.Lambda<Func<testItem, bool>>(containsMethodExp, parameter);

    return source.Where(predicate);
}
1

There are 1 answers

0
Alexandru Clonțea On

In order to use the StringComparison parameter, you need to correctly identify that method.

Is this what you need?:

public static IQueryable<testItem> PropertyContainsNEW(this IQueryable<testItem> source,
        Expression<Func<testItem, string>> selector,
        string value)
{
   var parameter = Expression.Parameter(typeof(testItem), "x");
   var property = Expression.Property(parameter, ((MemberExpression)selector.Body).Member.Name);
   var search = Expression.Constant(value, typeof(string));

   var parms = new Expression[] { search,
            Expression.Constant(StringComparison.OrdinalIgnoreCase) };

   var method = typeof(string).GetMethod("Contains", new[] { typeof(string), typeof(StringComparison) });
   var containsMethodExp = Expression.Call(property, method, parms);

   var predicate = Expression.Lambda<Func<testItem, bool>>(containsMethodExp, parameter);

   return source.Where(predicate);
}